Thursday, July 03, 2008

Formatting java log records

While configuring logging levels for different parts of your software is flexible in java logging, formatting log records are not. In terms of what is delivered with the jre you have two alternatives:
  1. SimpleFormatter
  2. XMLFormatter
None of these give you any choice on what to include. SimpleFormatter tells you todays date in every record, but not what thread is printing. XMLFormatter dumps everything, but since the xml file is not valid (at least not on mac) it is not easy to process, you have to edit it to make it valid first. So we decided to write our own formatter, which is not difficult. Here it comes:

public class ThreadFormatter extends Formatter {

public String format(LogRecord record) {
return "Thread-" +
record.getThreadID() + " " +
record.getMillis() % 10000 + " [" +
record.getSourceClassName() + ":" +
record.getSourceMethodName() + "] " +
record.getMessage() + "\n";
}
}

Most important change (besides printing it all on one line in a more compact format) is that the Thread ID is included. The date is actually not very interesting for us, we just display part of the timestamp to give a rough idea of what takes time in the system.

This works very well, when we run our application standalone or in NetBeans applet viewer. But when we run the application as an applet it will not (for security reasons) load the log formatter class. Feels like the guys at Sun didn't think about logging from applets when the designed java logging. What we would need is a standard log formatter where you can configure the log format, without needing to load your own class. Perhaps we will get that in a later version....

No comments: