Log a class with specific appender in Log4J

Log4J is a useful tool to log information from your application and write it into a separate file. In a big application, multiple entries from different classes are writing into the same file and it’s hard to follow the application flow for a specific class. For that reason, you can define an own appender for a specific class. The flow of this class will be written into a specific file with your defined log level. You can customize the log properties to your needs for the appender as same as you can define it for the root logger.

The following snippet contains a root logger and a specific logger:

#Root-Logger with Level INFO
log4j.rootLogger=INFO, file

# Log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=log/app.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

# specific logger with Level DEBUG
log4j.logger.org.foo.bar.FooBar=DEBUG, foobar
# don't write the logs into the root logger 
log4j.additivity.org.foo.bar.FooBar=false

log4j.appender.foobar=org.apache.log4j.RollingFileAppender
log4j.appender.foobar.File=log/foobar.log
log4j.appender.foobar.layout=org.apache.log4j.PatternLayout
log4j.appender.foobar.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

The org.foo.bar.Foobar is the full qualified class name of the class.

The property log4j.additivity.org.foo.bar.FooBar=false prevents to write the log entries of your specific logger into the root logger.

chevron_left
chevron_right

Leave a comment

Your email address will not be published. Required fields are marked *

Comment
Name
Email
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.