My new favorite log4j conversion pattern

log4j is a powerful logging utility for the Java programmers. Until now, I let other developers configure it. However, I was not satisfied with the configuration in my current project and took a deeper look.

The log4j pattern

Our logs were cumbersome, always displaying the full package, which is not always interesting. Dates varied from a log to another. So I looked for a standard conversion pattern I could use whenever I have to log something with log4j, and after some diving in the documentation, here is what I came up with:

An example of output

Some explanation

  • %d{ISO8601} – displays the date and time in the ISO format (see earlier post about this norm).
  • %-5p – the log level (such as DEBUG, INFO, WARN, …), formatted to occupy five columns (I like when things keep in line).
  • %t – the name of the thread logging this line.
  • %c{1} – the name of the class calling the logger (the {1} argument is there to restrict the number of packages displayed; {2} would display one package level before the class name, {3} would display two package levels, … and %c without the brackets would display the full package and class names).
  • %M – the method.
  • %L – the line number.
  • %m – the message to log.
  • %n – begin a new line.

There you are.