How do I configure Log4J with properties?
Author: Deron Eriksson
Description: This Java tutorial describes how to configure Log4J via a properties file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page: < 1 2 3 4

(Continued from page 3)

The PropertyConfigurator can also take a Properties object as an argument. In the Log4jPropertiesTest3 class below, we create a Properties object called log4jProperties and then set several properties on the object. We then pass log4jProperties as a parameter to PropertyConfigurator.configure().

Log4JPropertiesTest3.java

package test;

import java.util.Properties;

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

public class Log4JPropertiesTest3 {
	static Logger log = Logger.getLogger(Log4JPropertiesTest3.class);

	public static void main(String[] args) {
		Properties log4jProperties = new Properties();
		log4jProperties.setProperty("log4j.rootLogger", "ERROR, myConsoleAppender");
		log4jProperties.setProperty("log4j.appender.myConsoleAppender", "org.apache.log4j.ConsoleAppender");
		log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout", "org.apache.log4j.PatternLayout");
		log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout.ConversionPattern", "%-5p %c %x - %m%n");
		PropertyConfigurator.configure(log4jProperties);
		log.debug("This is a debug message");
		myMethod();
		log.info("This is an info message");
	}

	private static void myMethod() {
		try {
			throw new Exception("My Exception");
		} catch (Exception e) {
			log.error("This is an exception", e);
		}
	}
}

The execution of Log4JPropertiesTest3 is shown below.

Execution of Log4JPropertiesTest3

Notice that in the properties, we specified ERROR as the logging level. In the console output, we see that only the log.error message from our class is displayed.


As a final note, it's possible to initialize log4j by specifying a log4j properties file via a VM argument. This technique is illustrated here:

-Dlog4j.configuration=file:/C:/projects/workspace/testing/mylog4j.properties
Page: < 1 2 3 4