How to configure log4j

Log4j Installation

STEP -1 Download logging-log4j-1.2.15.zip
from
http://logging.apache.org/log4j/1.2/download.html
unzip it to  C:\ (Drive) eg: C:\logging-log4j-1.2.15

STEP-2 log4j-1.2.13.jar will be located in c:\logging-log4j-1.2.15\dist\lib directory

2.1 either append this path to Path(System variable in windows).

2.2 copy this jar to JAVA_HOME/JRE/lib/ext location
JAVA_HOME is a variable that points your jdk directory
eg: C:\jdk1.5.0_10


STEP -3  create a following file named log4j.properties and paste the following code
and save this file to
C:\jdk1.5.0_10\bin.

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{mm:ss} (%F:%M:%L)%n%m%n%n

STEP -4 create following Log4jTest.java and save it to C:\jdk1.5.0_10\bin

import org.apache.log4j.Logger;

public class Log4jTest {

static Logger log = Logger.getLogger(“com.javateacher.Log4jTest”);

public static void main(String args[]) {

log.debug(“This is my debug message.”);
log.info(“This is my info message.”);
log.warn(“This is my warn message.”);
log.error(“This is my error message.”);
log.fatal(“This is my fatal message.”);
}
}

STEP -5   compile it and run it as
C:\jdk1.5.0_10\bin> javac Log4jTest

and you will get Following output.

[DEBUG] 43:45 (Log4jTest.java:main:9)
This is my debug message.

[ INFO] 43:45 (Log4jTest.java:main:10)
This is my info message.

[ WARN] 43:45 (Log4jTest.java:main:11)
This is my warn message.

[ERROR] 43:45 (Log4jTest.java:main:12)
This is my error message.

[FATAL] 43:45 (Log4jTest.java:main:13)
This is my fatal message.


Congrats you have Successfully Run the First Log4j Example Successfully.

Leave a Reply