Web | This Site

log4j Tutorial
log4j Quick Guide
log4j Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# log4j - Sample Program

We have seen how to create a configuration file. This tutorial would teach you how to generate debug messages and log them in a simple text file.

Following is a simple configuration file created for our example. Let me re-iterate it once again:

- 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 means the printed logging message will be followed by a newline character.

So the content of log4j.properties file would be as follows:

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

    # Define the file appender
    log4j.appender.FILE=org.apache.log4j.FileAppender
    log4j.appender.FILE.File=${log}/log.out

    # Define the layout for file appender
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.FILE.layout.conversionPattern=%m%n

# Using log4j in Java Program:

The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.

    import org.apache.log4j.Logger;

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

    public class log4jExample{
      /* Get actual class name to be printed on */
      static Logger log = Logger.getLogger(
                          log4jExample.class.getName());

      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");
      }
    }

# Compilation and Run:

Here are the steps to compile and run the above mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. So do the following:

1. Create log4j.properties as shown above.

2. Create log4jExample.java as shown above and compile it.

3. Execute log4jExample binary to run the program.

You would get following result, inside /usr/home/log4j/log.out file:

    Hello this is an debug message
    Hello this is an info message

Advertisement

Online Image Processing

Indian Baby Names