In this tutorials we are going to see how to create simple log4j application using Basic Configurator with java program.Create java project called Log4jExample in your Eclipse IDE, then create package called com.javatutorialscorner.log4j.basic under log4j example,add log4j jar in your build path.I used log4j-1.2.17.jar jar for this application.you can download this jar from Apache web site
Now create java class called Log4jExample under com.javatutorialscorner.log4j.basic package
Log4jExample.java
package com.javatutorialscorner.log4j.basic;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
public class Log4jExample {
private static final Logger log = Logger.getLogger(Log4jExample.class);
public static void main(String args[]){
BasicConfigurator.configure();
log.debug("Debug message by Java Tutorials Corner");
log.info("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(Log4jExample.class) method accept fully qualified class name as its argument.
In this example BasicConfigurator.configure() used to initialize log4j using java class,you can also initialize log4j by propert file or xml file.Basic configurator takes console appender as default appender and SimpleLayout as default Layout
info,debug,warn,error,fatal are the levels available in log4j.we will see about log level in upcoming chapter
now you can run the application, you will see the following output in console.
0 [main] DEBUG com.javatutorialscorner.log4j.basic.Log4jExample - Debug message by Java Tutorials Corner
16 [main] INFO com.javatutorialscorner.log4j.basic.Log4jExample - Info message by Java Tutorials Corner
16 [main] WARN com.javatutorialscorner.log4j.basic.Log4jExample - Warn message by Java Tutorials Corner
16 [main] ERROR com.javatutorialscorner.log4j.basic.Log4jExample - Error message by Java Tutorials Corner
16 [main] FATAL com.javatutorialscorner.log4j.basic.Log4jExample - Fatal message by Java Tutorials Corner
0 comments:
Post a Comment