You are here

Quickly to log your code with log4j in 3 minutes

If you are one lazy programmer like me and have no time to read the document of log4j but still want to use log4j, try to read the following.

At least you'd better know that log4j is one tools to help you debug and log what happened with your code, anywhere and anywhen. I was used to use System.out.println() to debug my code, and I have written one function to do that:

/**
* Print out the debug message
* @param classname: Class object
* @param message: error or information message
*/
public static void debug(Class classname, String message){
if(Config.debugMode){
if(classname!=null){
System.out.println("-=Debug=- "+ message + " (in "+ classname+")");
}else{
System.out.println("-=Debug=- "+ message);
}
}
}

Call it in other class: debug(this.class,"something happens.") ;

ok, it works for my local java project, or when i tested my servlet code in localhost. But soonly I found one terrible thing when I upload my servlet web service to remote server: my logs has been flooded by thousands of logs from other service(Tomcat will log everything in catalina/logs/catalina.log or stdout_yyyymmdd.log). It is impossible to check my logs to know what happens. That why I must use log4j, at least it can log my service in one seperate log with.

The next 2 minutes, please:

1, download commons-logging-1.1.jar and log4j-1.2.14.jar, you could download other version as you can, just example here.

2, Import them into build path of your project, for servlet web service, put into WEB-INF/lib.

3, Create one text with named as log4j.properties in your src root path of you project(where your source code placing)

4, edit log4j.properties with following content:

#you can only log higher level logs, for example:
#
log4j.rootLogger=info, stdout, R
#debug<info<warn<error<fetal

log4j.rootLogger=debug, stdout, R

#stdout will output logs in console command line
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

#R will output logs in one log file
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=webapps/yourappname/yourappname.log
#record in new file when file size is over 1000kb
log4j.appender.R.MaxFileSize= 1000KB

# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%5p [%t(%d)] %c{1}:%L - %m%n

5, open any class in your project, add Logger
logger=Logger.getLog("yourclassname"); in your class, and call
logger.debug("debug
message") or logger.info("info message") or other methods to log your code. This is one example:

import com.foo.Bar;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class MyApp {
static Logger logger = Logger.getLogger(MyApp.class.getName());
public static void main(String[] args) {
try{
logger.debug("Entering application. args length: " +
args.lenth());
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}catch(Exception e){
logger.error("Error when run application");
}
}
}

6,restart your service in tomcat and run this class and you will find the log file in webapps/yourappname/yourappname.log.

DEBUG [main(2008-04-10 11:34:11,504)] (MyApp.java:8) - Entering application. args length:0
INFO [main(2008-04-10 11:34:11,504)] (MyApp.java:11) - Exiting application.

Ok, finished.

You can define differnt output log format , by changing the Layout.ConversionPattern, please refer
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

More information for lazy guys:

Log4j appender:
org.apache.log4j.ConsoleAppender (In Console)
org.apache.log4j.FileAppender
(In File)
org.apache.log4j.DailyRollingFileAppender (create one file everyday)
org.apache.log4j.RollingFileAppender (create one file when over size)
org.apache.log4j.WriterAppender (write logs with stream format to anywhere)


Config log layout formats:

log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
....
log4j.appender.appenderName.layout.option = valueN

Formats:
org.apache.log4j.HTMLLayout
(In HTML format )
org.apache.log4j.PatternLayout (In defined format flexible)
org.apache.log4j.SimpleLayout (include only log level and message)
org.apache.log4j.TTCCLayout (include only time, thread, class and message)




Layout.ConversionPattern:



  

%p priority output level: DEBUG,INFO,WARN,ERROR,FATAL
%r output time
%c class name
%t thread
%n new line, Windows
"\r\n", Unix "\n"
%d date, %d{yyy MMM dd HH:mm:ss,SSS}

%l position, line number, thread , exampleTestlog4.main(TestLog4.java:10)


 

Ref:

http://logging.apache.org/log4j
http://www.blogjava.net/rickhunter/articles/28133.html
http://www.infomall.cn/cgi-bin/mallgate/20031008/http://hedong.3322.org/...

Blog: