Thursday, July 30, 2009

Log4j Setting

After a long searching and discussions, I am able to do the logging for info, debug, error... You need three things in your hand.
1) Log4j.jar
That u can get it from here http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.15/apache-log4j-1.2.15.zip
2) Log4j.properties file
3) A text file where the messages will be printed.(say test.log)
Steps to follow
1) Add the log4j.jar in your library.
For that go to properties of your project
java build path
add external jars
browse and upload the jar file stored in your local system
2) Create a folder named "config" in your project outside src
3) Put the property file(log4j.properties) in the folder config
4) Again go to Project properties, java build path and click on the button Add class path folder
Browse the config folder and add it as the class path folder
5)That's all from the setting point of view
6)Now regarding the content in the property file, paste the following things
log4j.rootLogger=A1, A2
# A1 is set to be ConsoleAppender sending its output to System.out
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n
# Appender A2 writes to the file "test".
log4j.appender.A2=org.apache.log4j.FileAppender
log4j.appender.A2.File=D:/yourFolder/test.log
log4j.appender.A2.Append=true
# Appender A2 uses the PatternLayout.
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d %-5p [%t] %-17c{2} %-5r %-5p [%t] %c{2} - %m%n

7) In the class where you want to use log, write this as the first line of class
private static Logger log = Logger.getLogger(Test.class); after importing org.apache.log4j.Logger;
Then u can use like the following
log.info("Testing the info message");
log.error("Testing the error message");
log.debug("Testing the debug message");
8) Run the application
9) You can see the messages in the test.log file
Note:
a) Do not put log.info statements inside any loop in the code
b) While modifying the log4j.properties files do not say the Max size for test.log file and number of files. It can cause for exception saying "not enough space in device" or some thing like that.

0 Comments:

Post a Comment

<< Home