MTilsted
MTilsted

Reputation: 5545

log4j output to different files depending on class and level

What I want to do is very simple, but I can't seem to make it work with log4j.

I need 2 log files. The first should contain all debug statements of level debug or above but only from classes in my.app.*

The second log file should contain all messages of level warn and above, no matter the source class.

I tried the following config, but it don't work:

log4j.rootLogger=warn,root
log4j.appender.root=org.apache.log4j.FileAppender
log4j.appender.root.layout = org.apache.log4j.PatternLayout
log4j.appender.root.layout.conversionPattern = %d [%t] %-5p %c - %m%n
log4j.appender.root.file = /tmp/logs/warn.file
log4j.appender.root.append = true
log4j.appender.root.MaxFileSize=10MB
log4j.appender.root.MaxBackupIndex=7

log4j.logger.my.app=debug,debugAppender
log4j.appender.debugAppender = org.apache.log4j.RollingFileAppender
log4j.appender.debugAppender.file = /tmp/logs/my.debug.file
log4j.appender.debugAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.debugAppender.layout.conversionPattern = %d [%t] %-5p %c - %m%n
log4j.appender.debugAppender.append = true
log4j.appender.debugAppender.MaxFileSize=10MB
log4j.appender.debugAppender.MaxBackupIndex=7
log4j.additivity.my.app=false

I think the problem is with the last line. If I set additivity to true, then debug and info level messages will also be added to my warn.file. But if I set it to false, warnings from my.app only get logged to debug.file.

Upvotes: 4

Views: 3315

Answers (1)

ziesemer
ziesemer

Reputation: 28687

You'll want to make use of thresholds on each appender - exactly as described at Log Level per appender for a single Logger.

So leave the additivity set to true, and then add:

log4j.appender.root.Threshold=WARN

More details at http://logging.apache.org/log4j/1.2/faq.html#a2.9: "Is it possible to direct log output to different appenders by level?"

Just my additional $0.02: I'd recommend switching to the XML format instead of the properties format - which will prepare you nicely for migrating to SLF4J / Logback, as log4j is quickly being replaced with this worthy combination of a successor.

Upvotes: 4

Related Questions