Sunday, February 28, 2010

log4j - a good configuration

I was fine-tuning my log4j settings today and decided upon the config below (as regards the format of output). This was keeping in mind what could be grep-ed easily and that we had multiple users hit our test environment.

The NDC bit is particularly useful. It lets you track which user/client caused the log entry.

log4j.appender.R.layout.ConversionPattern=%d{ISO8601} %-5p %10t %x [%C{1}] - %m%n

%d{ISO8601} - date and its format

%-5p last 5 letters of the priority

%t - thread name

%x - Nested Diagnostic Context (NDC)

%C - Java class name, %C{1} will output the last one component

%m - log message

%n - new line

The code required for NDC in the classes is quite simple and is at the end of this post. Turns out NDC has a known memory leak issue which should not trouble you if you use the NDC.remove() method after completeing all your log statements. _______________________________

..

..

import org.apache.log4j.NDC;

..

..

NDC.push("any ID that helps you identify the client >>"+ID);

..

//all log statements

..

logger.debug("whatever");

..

NDC.pop();

NDC.remove();

I found most of the information at http://www.vipan.com/htdocs/log4jhelp.html.

No comments:

Post a Comment