Banner

Configure Log4J Programmatically for Stand-Alone Applications

Code Example

import org.apache.log4j.*;

import java.io.IOException;

public class LogTest {

  private static final Logger log = Logger.getLogger(LogTest.class);

  public static void main(String args[]) {
    //BasicConfigurator.configure();

    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    PatternLayout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);
    rootLogger.addAppender(new ConsoleAppender(layout));
    try {
      RollingFileAppender rfa = new RollingFileAppender(layout, "logtest.log");
      rfa.setMaximumFileSize(1000000);
      rootLogger.addAppender(rfa);
    } catch (IOException e) {
      // e.printStackTrace();
    } log.info("Testing...");
  }


}

Another possible PatternLayout to use for more readable format would be:

PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n");

Bookmark and Share
Comments
Name
Date (desc)
Comment
 
 
Comment Programmer

05/09/2011 9:58 am

Great Article.  Thanks for sharing


© 2024 - Blue Crown Software - (480) 306-6328 Register as New User Login