7.13. Configuring Log4J with a Properties File

Problem

You need to use Log4J, and you would like to configure it with a properties file.

Solution

Use the BasicConfigurator to read a log4j.properties file resource from the classpath. The following code configures Log4J from a resource named log4j.properties, and logs two messages:

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;

URL log4Jresource = this.getClass( ).getResource("log4j.properties");
PropertyConfigurator.configure( log4Jresource );

Logger log = Logger.getLogger( "com.discursive.SomeApp" );
log.info( "This is a log message" );
log.error( "This is an error message" );

The log4j.properties file contains a basic Log4J configuration that sets the root category logging level to WARN and the application’s logging level to DEBUG:

# All logging output sent to standard out and a file # WARN is default logging level log4j.rootCategory=WARN, STDOUT, FILE # Application logging level is DEBUG log4j.logger.com.discursive=DEBUG # Configure the Standard Out Appender log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout log4j.appender.STDOUT.layout.ConversionPattern=%5p (%F:%L) %m%n # Configure a rolling file appender log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=output.log log4j.appender.FILE.MaxFileSize=2000KB log4j.appender.FILE.MaxBackupIndex=5 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%d ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.