First, include
Log4j jar file in your project (e.g. log4j-1.2.8.jar)
From http://www.javabeat.net/tips/82-baisc-steps-to-configure-log4j-using-xml-and.html
This example program uses simple satndalone java program for running the example. But, in most of the project scenarios it will be used in the web application. However the configuration file will be the same.
From http://www.javabeat.net/tips/82-baisc-steps-to-configure-log4j-using-xml-and.html
Configure Log4j
This example demonstrated how to configure Log4j setup using the Proerties file and XML file. These are the two most widely used techniques for configuring the Log4j for your application. But, in the recent days configuring with properties files are considered to be old technique and recommended using XML.This example program uses simple satndalone java program for running the example. But, in most of the project scenarios it will be used in the web application. However the configuration file will be the same.
log4j.properties
# Set root logger level to DEBUG and its only appender to Appender1.
log4j.rootLogger=INFO, Appender1,Appender2
# Appender1 is set to be a ConsoleAppender.
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender2=org.apache.log4j.RollingFileAppender
log4j.appender.Appender2.File=sample.log
# Appender2 uses PatternLayout.
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.xml
Log4jPropertyTest.java
package javabeat.net.log4j;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* source : www.javabeat.net
*/
public class Log4jPropertyTest {
private static Logger logger = Logger.getLogger(Log4jPropertyTest.class);
public static void main (String args[]){
PropertyConfigurator.configure("log4j.properties");
logger.info("Test Log");
}
}
Log4jXmlTest.java
package javabeat.net.log4j;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
/**
* source : www.javabeat.net
*/
public class Log4jXmlTest {
private static Logger logger = Logger.getLogger(Log4jXmlTest.class);
public static void main (String args[]){
DOMConfigurator.configure("log4j.xml");
logger.info("Test Log");
}
}
Comments
Post a Comment