Logger.java 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.zipcoder.server;
  2. import java.io.*;
  3. import java.net.URISyntaxException;
  4. public class Logger {
  5. private enum Type{
  6. INFO, ERROR;
  7. }
  8. public static void info(String message) {
  9. log(Type.INFO, message);
  10. }
  11. public static void error(String message, Exception e) {
  12. log(Type.ERROR, message);
  13. PrintWriter writer = getWriter();
  14. e.printStackTrace(writer);
  15. closeWriter(writer);
  16. }
  17. private static void log(Type type, String message) {
  18. Writer writer = null;
  19. try {
  20. writer = writeMessage(type, message);
  21. } catch (IOException e) {
  22. System.err.println("Unable to write message");
  23. e.printStackTrace();
  24. } finally {
  25. closeWriter(writer);
  26. }
  27. }
  28. private static Writer writeMessage(Type type, String message) throws IOException {
  29. Writer writer = getWriter();
  30. writer.append(type.name() + ": " + message + "\n");
  31. return writer;
  32. }
  33. private static void closeWriter(Writer writer) {
  34. try {
  35. if (writer != null){
  36. writer.close();
  37. }
  38. } catch (IOException e) {
  39. System.err.println("Unable to close log file.");
  40. }
  41. }
  42. private static PrintWriter getWriter() {
  43. PrintWriter writer = null;
  44. try {
  45. writer = new PrintWriter(new FileWriter(getLogFile(), true));
  46. } catch (Exception e) {
  47. handleException(e);
  48. writer = new PrintWriter(System.out);
  49. }
  50. return writer;
  51. }
  52. private static File getLogFile() throws URISyntaxException, IOException {
  53. File file = new File(Config.PUBLIC_DIRECTORY + Config.LOG_PATH);
  54. if (!file.exists()){
  55. file.createNewFile();
  56. }
  57. return file;
  58. }
  59. private static void handleException(Exception e) {
  60. System.err.println("Unable to open log file.");
  61. e.printStackTrace();
  62. }
  63. }