001 package toolbus.logging;
002
003 import java.io.File;
004 import java.io.FileOutputStream;
005 import java.io.IOException;
006 import java.io.PrintWriter;
007
008 /**
009 * Logger implementation that writes to a file.
010 *
011 * @author Arnold Lankamp
012 */
013 public class FileLogger implements ILogger{
014 private final static String endLineCharacter = System.getProperty("line.separator");
015
016 private final int level;
017
018 private final PrintWriter writer;
019
020 private boolean timestamp = false;
021
022 /**
023 * Default constructor. Inititalizes this logger with the default log level (WARNING).
024 */
025 FileLogger(){
026 this(ILogger.WARNING);
027 }
028
029 /**
030 * Constructor. Initialized this logger with the given log level.
031 *
032 * @param level
033 * The log level to initialize this logger with.
034 */
035 FileLogger(int level){
036 super();
037
038 this.level = level;
039
040 try{
041 // TODO make configurable.
042 writer = new PrintWriter(new FileOutputStream(new File("./toolbus.log"), true));
043 }catch(IOException ioex){
044 throw new RuntimeException(ioex);
045 }
046 }
047
048 /**
049 * Method for checking if we should log a message. This depends on the log level and the given
050 * log level.
051 *
052 * @param loglevel
053 * The log level of the message.
054 * @return True if we should log the message with the given log level, false otherwise.
055 */
056 private boolean shouldLog(int loglevel){
057 return (this.level >= loglevel);
058 }
059
060 /*
061 * @see toolbus.logging.ILogger#setTimestamp(boolean)
062 */
063 public void setTimestamp(boolean on) {
064 timestamp = on;
065 }
066
067
068 /**
069 * @see ILogger#log(String, int)
070 */
071 public void log(String message, int loglevel){
072 if(shouldLog(loglevel)){
073 synchronized(writer){
074 if(timestamp){
075 writer.print("[");
076 writer.print(CommandLineLogger.getFormattedDateTime());
077 writer.print("] - ");
078 }
079 writer.print(CommandLineLogger.getLogLevelString(loglevel));
080 writer.print(" - ");
081 writer.print(message);
082 writer.print(endLineCharacter);
083
084 writer.flush();
085 }
086 }
087 }
088
089 /**
090 * @see ILogger#log(String, Throwable, int)
091 */
092 public void log(String message, Throwable throwable, int loglevel){
093 if(shouldLog(loglevel)){
094 synchronized(writer){
095 if(timestamp){
096 writer.print("[");
097 writer.print(CommandLineLogger.getFormattedDateTime());
098 writer.print("] - ");
099 }
100 writer.print(CommandLineLogger.getLogLevelString(loglevel));
101 writer.print(" - ");
102 writer.print(message);
103 writer.print(endLineCharacter);
104
105 throwable.printStackTrace(writer);
106 writer.print(endLineCharacter);
107
108 writer.flush();
109 }
110 }
111 }
112
113 /**
114 * Closes this logger.
115 */
116 public void finalize(){
117 writer.close();
118 }
119 }