Wednesday, July 17, 2013

How to configure Log4j ConsoleAppender

Log4j ConsoleAppender is used to print logs in application console. You can configure this in log4j.properties file or by java code.

 Configuring ConsoleAppender in log4j.properties file


Following is the basic configuration for ConsoleAppender.
log4j.rootLogger = DEBUG, myConsole
log4j.appender.myConsole = org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout = org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern = %-5p %m%n

In first line we set the logging level of rootLogger to DEBUG, and define the name for a Appender.
You can use any logging level such as INFO, WARN, ERROR etc. instead of DEBUG according to your requirement. For an example if you set the level to WARN, only the log entries with level equal or higher than WARN will be printed. The default level of rootLogger is DEBUG.
'myConsole' is the name of the Appender you are going to create. You can define more Appenders by adding them by separating with commas.

Example:
log4j.rootLogger = INFO, myConsole, myInfoFile,....

In second line we register 'myConsole' as a ConsoleAppender.

Third and fourth lines define the pattern for the log entry.

Now in your Java class you can access this Appender as below.
import org.apache.log4j.*;
public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);
  public static void main(String[] args) {
    logger.info("This is info.");
    logger.error("This is error.");
  }
}


 Configuring ConsoleAppender from java code


import org.apache.log4j.*;

public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);

  public static void main(String[] args) {
    PatternLayout layout = new PatternLayout("%-5p %d %m%n");
    ConsoleAppender appender = new ConsoleAppender(layout);
    appender.setName("consoleLog");
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);

    logger.setLevel(Level.WARN);
    logger.info("This is info.");
    logger.error("This is error.");
  }
}

No comments:

Post a Comment