Monday, September 7, 2009

Java logging "message duplication" phenomenon

I've been stuck with this problem for a while and googled a lot on it before the resolution struck me. But firstly, what was the problem?

Problem Definition: There are times in multi-threaded java programming when you see duplicate messages in your log files.

What was I doing wrong: I had setup the logging infrastructure in a super class that all logging classes would extend. Everytime I was instantiating a class that would log it would initialize the logging infrastructure for itself. And everytime it did so it would add another Appender(log4j)/Handler(JUL) to the Logger class.

What is the resolution: Do this in the log setup code(specific for log4j):

Logger logger = Logger.getLogger("");
Enumeration appenders = logger.getAllAppenders();
if (!appenders.hasMoreElements()) {
//initialize an Appender class
//Add the appender object to the logger
}

When I was doing it wrongly, I did not have the if block. Hope you would benefit from this piece of wisdom :)

No comments: