Davio
Davio

Reputation: 4737

Log4j: Different log levels for subpackages

Let's say I have the following log4j.properties:

# Root logger option
log4j.rootLogger=INFO, stdout
# Direct normal log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c{1}:%L - %m%n

# Application logs
log4j.logger.com.company.app=DEBUG, file
log4j.additivity.com.company.app=false
log4j.logger.com.company.app.sub=TRACE, file
log4j.additivity.com.company.app.sub=false

# Direct application log messages to a custom log file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${com.sun.aas.instanceRoot}/logs/app.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd-a
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c{1}:%L - %m%n

So I want to log messages that don't come from my app to console, messages that I create in my own log and have a different level for messages of my subpackage.

When I try it like this I get messages for my subpackage twice, even with additivity set to false.

What I'm trying to achieve is log all messages from my application exactly once (not to the main log, but to my own file), but to be able to set different levels for subpackages.

I'm using log4j v 1.2 and SLF4J as a front.

Upvotes: 3

Views: 4123

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

You don't need to attach the file appender twice, just attach it once at the com.company.app level and let additivity do the right thing:

# Application logs
log4j.logger.com.company.app=DEBUG, file
log4j.additivity.com.company.app=false
log4j.logger.com.company.app.sub=TRACE

Here com.company.app.sub will inherit the file appender from its parent com.company.app but inheritance will stop here because of the additivity setting so it won't inherit the stdout appender from the root logger.

Upvotes: 4

Related Questions