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 2)

Of course, placing a properties file at the top of your source directory does have its limits. Thankfully, the PropertConfigurator class lets you solve this problem, since you can pass it the location/name of the log4j properties file that you would like to use.

Let's create a file at the root level of our project.

'' at root level of project

The file is shown below. It is very similar to the file that we saw earlier. Note that the log level is set to DEBUG.

# This sets the global logging level and specifies the appenders
log4j.rootLogger=DEBUG, myConsoleAppender

# settings for the console appender
log4j.appender.myConsoleAppender.layout.ConversionPattern=%-5p %c %x - %m%n

This project contains a Log4JPropertiesTest2 class that is just like the Log4JPropertiesTest class except that it features the following line:


This line initializes log4j with the configuration properties specified in

package test;

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

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

	public static void main(String[] args) {
		log.debug("This is a debug message");
		myMethod();"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);

In the EclipseSW debug configuration, I don't have the VM -Dlog4j.debug=true argument present in the earlier example. For normal use, typically this argument is not present. If we run Log4JPropertiesTest2, we see the following:

Execution of Log4JPropertiesTest2

As you can see, the ConsoleAppender outputs our log messages to the console according to the pattern that we specified in

(Continued on page 4)

Page: < 1 2 3 4 >