log4j logging to DB (in a cluster)

1.3k views Asked by At

I have a Java application which runs on two machines in a cluster and they both log to one MySQL database. Everything works fine, but I would like to have an additional field in the database which represents the IP where the requests is coming from.
I solved this by having two different log4j.properties files, but I guess there is a nicer way to do that?

This is the line in the log4j.properties file that is different on the machines:

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, message) VALUES ('%d{dd MMM yyyy HH:mm:ss,SSS}','%c','%p','10.20.30.40','%m')

Is there something for MySQL like connection_ip? Or a placeholder in log4j, so that I could store the IP in there from the Java application?

1

There are 1 answers

0
Nussmischung On BEST ANSWER

I solved this by using the Mapped Diagnostic Context of log4j. When I start the Java application I store the IP with this command.

MDC.put("serverIP", InetAddress.getLocalHost().getHostAddress());

And now I can use the %X{serverIP} as a placeholder in my log4j.properties file.

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, sessionID, message) VALUES ('%d{dd/MM/yyyy HH:mm:ss,SSS}','%c','%p','%X{serverIP}','%X{sessionID}','%m')

Here is a excellent post about log4j with a few good examples
http://onjava.com/pub/a/onjava/2002/08/07/log4j.html?page=3