I currently have the below pattern layout in log4j. I want to add the Process id to the log file. How can I do it?
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
Pasted sample log message
2011-01-07 11:48:21,940 [main] INFO Testing1
2011-01-07 11:48:21,942 [main] INFO Test.common.ApplicationProperties - Used log4j
"log4j.properties" [Read only] 26 lines, 884 characters
log4j.rootCategory=DEBUG, stdout, A1
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=WARN
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} %-5p (%c) %m%n
log4j.appender.A1=org.apache.log4j.RollingFileAppender
log4j.appender.A1.Threshold=DEBUG
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.A1.File=/homw/cus/logs/ccl.02.log
log4j.appender.A1.MaxFileSize=5MB
log4j.appender.A1.MaxBackupIndex=40
log4j.category.test.common.DBConnectionPool=WARN
log4j.category.test.common.DataBaseHandler=WARN
log4j.category.test.cttg.tables=WARN
log4j.category.test.middleware.tables=WARN
log4j.logger.org.apache.axis=ERROR
log4j.logger.org.apache.catalina=ERROR
You should use MDC to do it
In the config file :
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} %-5p (%c) %m%n %X{PID}
%X{PID}
is used to match the context value PID
And then, in the code, before the logging begins :
log4j 1.x
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
String pid = rt.getName();
MDC.put("PID", pid);
log4j 2.x
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
String pid = rt.getName();
ThreadContext.put("PID", pid);