Thursday, May 19, 2005

Log4J and PatternLayout

I recently moved all the logging in Bodington to use Log4J. Now when I originally did the translation I wanted the logs to look very similar to the output produced by java.util.logging to ease the transition. Under java.util.logging when an message is logged with an Exception object the stack trace from the Exception is written to the logs as well as the message which is often very useful. Now looking at the Log4J JavaDocs for 1.2.9 it said that only XMLLayout would deal with the Exceptions in the logging calls. Because of this I decided I would write a simple Log4J Layout that would write the stack trace to the logs. The result was a class called SimpleThrowableLayout. Now although this class works well it is nowhere near as flexible as PatternLayout (it extends TTCCLayout), but I was reasonably pleased with it. However the other day when testing some different logging setups I discovered that PatternLayout does actually output the stack trace to the logs when you ask it to output the message (%m). I was not very happy! But at least I now have a better understanding about how to write a Log4J layout. NB: PatternLayout has undergone a major refactoring in the later Log4J revisions and the JavaDoc has been corrected so hopefully this shouldn't bite too many other people.