What is Log4J and how do I use it?
Author: Deron Eriksson
Description: This Java tutorial gives an overview of how to use Log4J for logging in your applications.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page: < 1 2

(Continued from page 1)

Let's make some trivial tweaks to the test class and execute it, as shown below.

Execution of Log4JTest

In this example, I changed the logger's identifier to be "bacon" rather than the class name. However, it's typical to use the class's name as its identifier. I added a method that throws and catches an exception, and displays an exception message and the stack trace for that exception. It also displays an info message.

Although the Log4JTest class is trivial and not very useful, it's included below.

Log4JTest.java

package test;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Log4JTest {
	static Logger log = Logger.getLogger("bacon");

	public static void main(String[] args) {
		BasicConfigurator.configure();
		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);
		}
	}
}
Page: < 1 2