How to attach a single class to a Log4J appender?
The issue looks simple, but I needed a little search.
Case
I have a log4j config file, with three appenders: INFO,
console
and trace
. I have to add a brand new appender (let’s say: JonathanNewAppender
) that will log the events of only one class (let’s say: JonathanComponent
). How to configure Log4J to perform that?
Solution
Edit the log4j.properties
file.
Do not change the property log4j.rootCategory
, do not mention JonathanNewAppender
.
[java]log4j.rootCategory=INFO, console, trace[/java]
Add the properties of the appender, for instance: Donner les proprietes de l’appender:
[java]log4j.appender.JonathanNewAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.JonathanNewAppender.Append=true
log4j.appender.JonathanNewAppender.File=logs/prsl-sent-and-received.csv
log4j.appender.JonathanNewAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.JonathanNewAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss}%m%n
log4j.appender.JonathanNewAppender.threshold=INFO[/java]
And here is the trick: add the log level and the actual appender for the new class.
[java]log4j.logger.my.package.name.JonathanComponent=INFO, JonathanNewAppender[/java]
Indeed, the only field of a logger to be mandatory is the log level. When the appender is specified, it will be taked in account. Otherwise, the logger will be attached all the appenders available in log4j.rootCategory
property.