Tuesday, October 23, 2012

log4j Configuration Tips

Here are some of the tips/mistakes/solutions that I stumbled upon while configuring log4j. I am making a note for myself in case I need them in the future.

Variables. If you use PropertyConfigurator to configure logging, you can use the ${...} notation in the configuration file. E.g. in log4j.properties:

log4j.appender.A1.File=${user.home}/log/app.log

The catch is you can only use System variables defined in java.lang.System.

Layout pattern.
  • To indicate EOL, use %n, not \n.
  • %-5p is better than %6p as the log level will be left-aligned and you save 1 character per message.
  • %5t doesn't do what you want it to do, just use %t.

NDC. Although the use of NDC is discouraged, I find that, when used properly, it helps in troubleshooting. E.g. in the MDB's onMessage(), you can push some unique identifier to the NDC by using NDC.push(s). For example, transaction number, account number, customer number, etc. The value will appear if you also add %x in the pattern. Remember to call NDC.remove() before your return from the MDB. Pattern:

NDC.push(id);
try {
    ...
}
finally {
    NDC.pop();
    if (NDC.getDepth() == 0) {
        NDC.remove();
    }
}

Logger syntax.

log4j.logger.some.package=INFO,appender


Additivity syntax.

log4j.additivity.some.package=false

Note that some web sites write log4j.some.package.additivity=false but PropertyConfigurator is looking for the prefix log4j.additivity.

log4j.properties & log4j.xml in the same folder. I noticed that when both files are found in the same folder, log4j.properties seems to have priority than the XML file unless your code specifically looks for log4j.xml.

Class name. Don't use %c because full class names are usually very long. Don't use %c{1} because you can't tell which package the class is in. I suggest you try %c{2}, which prints the last 2 components of the full class names, e.g. util.Date.

No comments: