log4j Tutorial - Log4j HelloWorld

We use the following configuration file to control the log4j.

The level of the root logger is defined as DEBUG and attaches appender named FILE to it.

The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.

The layout pattern defined is %m%n, which prints logging message ending with a newline character.

# Define the root logger with appender file
log = c:/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender

# Define the layout for file appender

log4j in Java Code

The following Java class shows how to use Log4J logging library.

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class Main {
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(

  public static void main(String[] args)
                throws IOException,SQLException{
     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");

All the libraries should be available in CLASSPATH and the log4j.properties file should be available in PATH.