Saturday, August 17, 2013

Filter specific log level in log4j configuration

Usually when I want to log something, I'll do this:
private static void Logger logger = Logger.getLogger("MyClass.class");

public void functionA() {
   log.error("blah blah blah");
}
We all knew that log4j have different log level, such as TRACE < DEBUG < INFO < WARN < ERROR < FATAL, and there are inheritance. Meaning if log4j is being configure to accept log at INFO level, the log at WARN, ERROR, and FATAL will be capture as well. How does it look like in the code?
public void functionA() {
   log.error("blah blah blah");

   ...
   ...

   log.info("ha hah hahh");
}
The above code sample will have both info log and error log being logged. If log level is set to ERROR, only "blah blah blah" will be log. Anything below ERROR log level will not be log. This is what we usually did on log4j. So what if I want to log only INFO level? I been told that log4j.additivity is for this purpose. But I failed to configure it. Anyhow I got an alternate solution, by using filter in log4j configuration.
log4j.appender.APP.threshold = info
log4j.appender.APP.filter.a=org.apache.log4j.varia.LevelMatchFilter
log4j.appender.APP.filter.a.LevelToMatch=info
log4j.appender.APP.filter.a.AcceptOnMatch=true
log4j.appender.APP.filter.b=org.apache.log4j.varia.LevelMatchFilter
log4j.appender.APP.filter.b.LevelToMatch=warn
log4j.appender.APP.filter.b.AcceptOnMatch=false
log4j.appender.APP.filter.b=org.apache.log4j.varia.LevelMatchFilter
log4j.appender.APP.filter.b.LevelToMatch=error
log4j.appender.APP.filter.b.AcceptOnMatch=false
log4j.appender.APP.filter.b=org.apache.log4j.varia.LevelMatchFilter
log4j.appender.APP.filter.b.LevelToMatch=fatal
log4j.appender.APP.filter.b.AcceptOnMatch=false
The above configuration will do the job.

No comments: