0

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?

PandaBearSoup
  • 699
  • 3
  • 9
  • 20

2 Answers2

2

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.

PandaBearSoup
  • 699
  • 3
  • 9
  • 20
1

Filehandler Tutorial

This tutorial show that you have to flush and then close the Handler after adding the Message.

Zeh
  • 186
  • 2
  • 8
  • I flush the handler after each time I log, and close the handler before closing the application. – PandaBearSoup Jun 25 '13 at 14:24
  • I am sorry, I completely misunderstood your question. I thought no line was added to the text at all, not only new lines. Nice job finding the answer, though! – Zeh Jun 25 '13 at 14:41