Saturday, 17 August 2013

Log4j Example using Property File

In this tutorials we are going to see how to create simple log4j application using Property Configurator with java program, previously we have seen log4j application using Basic Configurator we can obtain same output using property file.
Create java project called Log4jExample in your Eclipse IDE, then create package called under log4j example,add log4j jar in your build path.I used log4j-1.2.17.jar jar for this can download this jar from Apache web site.Create in your project directory or source directory, add the following configuration
log4j.rootLogger= Debug,console


log4j.appender.console.layout.ConversionPattern=%r [%t] %p %c %x - %m%n

rootLogger used to configure Level and Appender, in this example I used DEBUG as Level and Console appender as appender(console is name of appender).

PatternLayout is used to configure log4j message format.We will see Pattern Layout in detail in upcoming chapter.

Now create java class called Log4jPropertyExample under  package.


import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jPropertyExample {

private static final String FILE_PATH = "";
private static final Logger log = Logger

* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
if (FILE_PATH == null) {
BasicConfigurator.configure();"Log4j Configured using Basic Configurator");
} else {
PropertyConfigurator.configure(FILE_PATH);"Log4j Configured using Property Configurator");

log.debug("Debug message by Java Tutorials Corner");"Info message by Java Tutorials Corner");
log.warn("Warn message by Java Tutorials Corner");
log.error("Error message by Java Tutorials Corner");
log.fatal("Fatal message by Java Tutorials Corner");


Create instance for Logger class , getLogger(Log4jPropertyExample .class) method accept fully qualified class name as its argument. In this example if property file not exist in specified location then BasicConfigurator.configure() used to initialize log4j application otherwise  PropertyConfigurator.configure(FILE_PATH)  loads the configuration from property file .

now you can run the application, you will see the following output in console.

0 [main] INFO  - Log4j Configured using Property Configurator

0 [main] DEBUG  - Debug message by Java Tutorials Corner

0 [main] INFO  - Info message by Java Tutorials Corner

0 [main] WARN  - Warn message by Java Tutorials Corner

0 [main] ERROR  - Error message by Java Tutorials Corner

0 [main] FATAL  - Fatal message by Java Tutorials Corner


Post a Comment