Working with Log4J Basics – A Log4J Tutorial

Configuring with log4j.properties

If the Log4J API doesn’t find the log4j.xml file it will try to look for log4j.properties file in the src directory. Below is the sample log4j.properties file to configure logger in the application.


#Log messages to Console
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{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout

If you execute the same code using the log4j.properties file you will get the log output on the console as


14:01:58,308  INFO ConfigureLog4J:25 - Entering application.
14:01:58,339  INFO ConfigureLog4J:27 - Exiting application

log4j.xml versus log4j.properties

Properties can be defined by a properties file or by an XML file. Log4j looks for a file named log4j.xml and then for a file named log4j.properties. Both must be placed in the src folder. The property file is less verbose than an XML file. The XML requires the log4j.dtd to be placed in the source folder as well. The XML requires a dom4j.jar which might not be included in older Java versions.

The properties file does not support some advanced configuration options like Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers defines how errors in log4j itself are handled, for example badly configured appenders. Filters are more interesting. From the available filters, I think that the level range filter is really missing for property files. This filter allows defining that an appender should receive log messages from Level INFO to WARN. This allows splitting log messages across different logfiles. One for DEBUGGING messages, another for warnings.

The property appender only supports a minimum level. If you set it to INFO, you will receive WARN, ERROR and FATAL messages as well.

Please Post Your Comments & Reviews

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

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