I am following this guide to output Logger info to a File with a formatted FileHandler.
public class TestLog {
public static Logger logger;
static {
try {
boolean append = true;
FileHandler fh = new FileHandler("TestLog.log", append);
fh.setFormatter(new Formatter() {
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
The guide shows the output will print each new logger message on a new line,
Mon Feb 28 21:30:54 EST 2005 SEVERE my severe message
Mon Feb 28 21:30:54 EST 2005 WARNING my warning message
Mon Feb 28 21:30:54 EST 2005 INFO my info message
However, no new line is being appended in the file, or they are on the StringBuffer and then a new one is created and it is lost somehow. Can someone explain the issue here? Thanks.
My method/logger are not static, could this be causing the problem?
I was able to solve the problem. The tutorial constructs the formatter as such,
fh.setFormatter(new Formatter() {
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
The problem is that this does not actually append a new line in the file, instead of using
buf.append('\n');
you need to use
buf.append(System.getProperty("line.separator"));
My file now is readable, not a mess of connected lines. Hope this helps someone in the future.