You are here

Quickly to log your code with log4j in 3 minutes

Blog Terms: 

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){
System.out.println("-=Debug=- "+ message + " (in "+ classname+")");
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 in your src root path of you project(where your source code placing)

4, edit with following content:

#you can only log higher level logs, for example:
log4j.rootLogger=info, stdout, R

log4j.rootLogger=debug, stdout, R

#stdout will output logs in console command line
# 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
#record in new file when file size is over 1000kb
log4j.appender.R.MaxFileSize= 1000KB

# Keep one backup file

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
message") or"info message") or other methods to log your code. This is one example:

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) {
logger.debug("Entering application. args length: " +
Bar bar = new Bar();
bar.doIt();"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)] ( - Entering application. args length:0
INFO [main(2008-04-10 11:34:11,504)] ( - Exiting application.

Ok, finished.

You can define differnt output log format , by changing the Layout.ConversionPattern, please refer

More information for lazy guys:

Log4j appender:
org.apache.log4j.ConsoleAppender (In Console)
(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 =
log4j.appender.appenderName.layout.option1 = value1
log4j.appender.appenderName.layout.option = valueN

(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)



%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(