How to apply a log4j conversionPattern to a specific package?

Viewed 572

I want to add an ID to all logs that originate from classes in a particular package - com.example.package.

In order to achieve this, I'm using Mapped Diagnostic Context (MDC) and log4j's layout conversion patterns.

In the code, I set the ID via MDC.put("correlation.id", id);

Then, I created a log4j.properties file, with the following content:

log4j.rootLogger=WARN,myappender

log4j.appender.myappender=org.apache.log4j.ConsoleAppender
log4j.logger.com.example.package=INFO,myappender
log4j.additivity.com.example.package=false

log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=<%-4p> %d{yyyy-MMM-dd::HH:mm:ss,SSS}  %C{1} %t: - %m - correlation.id=%X{correlation.id}%n

This works for the specific package. However some packages that were previously logging at an INFO level, don't appear anymore. I believe the first line is setting the level to WARN globally. By default some packages are on WARN and others on INFO, so I don't want to set a global level. I tried deleting the line but without it I get this error:

log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

In the end, I don't want to affect logging globally, I really just want to apply that conversion pattern to that particular package and leave everything else as before I created the log4j.properties file.

Is this possible?

1 Answers

You can define multiple appenders in log4j, so you could use a default appender like this:

log4j.rootLogger=INFO, myDefaultAppender

for all packages

and additional appenders for some other packages like this:

log4j.logger.com.example.package1=WARN, myEmailAppender, myFileAppender
log4j.logger.com.example.package2=DEBUG, myFileAppender
Related