98..Etc/Log4J2008. 7. 8. 17:39
반응형

A simple Log4J example

By Alvin J. Alexander, devdaily.com

The following class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications. As you can see the configuration is pretty simple.

package com.devdaily.log4jdemo;

import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

public class Log4JDemo
{
  static final Category log = Category.getInstance(Log4JDemo.class);
  static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties";

  public static void main(String[] args)
  {
    // call our constructor
    new Log4JDemo();
    // Log4J is now loaded; try it
    log.info("leaving the main method of Log4JDemo");
  }

  public Log4JDemo()
  {
    initializeLogger();
    log.info( "Log4JDemo - leaving the constructor ..." );
  }

  private void initializeLogger()
  {
    Properties logProperties = new Properties();

    try
    {
      logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
      PropertyConfigurator.configure(logProperties);
      log.info("Logging initialized.");
    }
    catch(IOException e)
    {
      throw new RuntimeException("Unable to load logging property " + LOG_PROPERTIES_FILE);
    }
  }
}

After a few class level fields are created, the action begins with the main method, which first calls the constructor for this class. The constructor then calls the initializeLogger method. This method actually does the work of loading the Log4J properties file. It then calls the configure method of the PropertyConfigurator class.

Once this is done I call the info method of the log object several times. Notice that I could have also called other methods like logger.warn(), log.debug(), log.error(), or log.fatal(), but to keep it simple I'm just showing log.info().

The Log4J Properties File

Before I leave this quick tip I also need to show the Log4J properties file that I'm using. My file is named Log4J.properties, and for the purpose of this demonstration I'm keeping it in a sub-directory of my project named lib. Here are the contents:

# STDOUT appender
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d %p [%t] %C{1} - %m\n

# use the STDOUT appender. set the level to INFO.
log4j.category.com.devdaily.log4jdemo.Log4JDemo=INFO, STDOUT


Posted by 1010