Configure log4j in eclipse without using log4j.properties file - Java @ Desk

Saturday, June 8, 2013

Configure log4j in eclipse without using log4j.properties file

Log4J Implementation in Eclipse without using log4j.properties file:
There are three implementations for configuration of log4j in eclipse.

Required files for the implementation are:
1) log4j.jar
Create a new Java project and name it as LoggerImpl
Create package com.logger and create Log4JPropertyFile.java

package com.logger;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;

public class Log4JPropertyFile {
 static Logger log = Logger.getLogger(Log4JPropertyFile.class);

 public static void main(String[] args) {

 Properties log4jProperties = new Properties();
 log4jProperties.setProperty("log4j.rootLogger", "INFO, myConsoleAppender");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender", "org.apache.log4j.ConsoleAppender");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout", "org.apache.log4j.PatternLayout");
 log4jProperties.setProperty("log4j.appender.myConsoleAppender.layout.ConversionPattern", "%-5p %c %x - %m%n");
 PropertyConfigurator.configure(log4jProperties);

 log.debug("This is a debug message");
 log.info("This is an info message");
 }
}


Output:

0    [main] INFO  com.logger.Log4JImplementation  - This is an info message

As you can see, only the info message is visible in console but the debug message is not printed. This is because of the debug level set to INFO in java file. Change the properties as shown below:

log4jProperties.setProperty("log4j.rootLogger", "DEBUG, myConsoleAppender");

Output:

0    [main] DEBUG com.logger.Log4JImplementation  - This is a debug message
0    [main] INFO  com.logger.Log4JImplementation  - This is an info message

Other references on log4j implementation in eclipse
How to configure log4j in eclipse
Configure log4j in eclipse using PropertyConfigurator class
Configure log4j in eclipse without using log4j.properties file







No comments:

Post a Comment