Tuesday, 11 September 2012

Configuring Log4j with Java Web Applications + Tomcat

Log4j -  is a Java-based logging utility. Next i will explain hot to configure it with Web App + tomcat.
1) First you should create log4j.properties file:

log4j.logger.appnamelogger=DEBUG, C, fileappender
 
log4j.additivity.appnamelogger=false
log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.layout=org.apache.log4j.PatternLayout
#basic pattern
log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n
#advanced pattern (slow)
#log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m - in %M() at line %L of class %C %n
 
log4j.appender.fileappender=org.apache.log4j.RollingFileAppender
log4j.appender.fileappender.File=${appRootPath}WEB-INF/logs/appname.log
log4j.appender.fileappender.MaxFileSize=500KB
 
## Keep one backup file
log4j.appender.fileappender.MaxBackupIndex=3
log4j.appender.fileappender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileappender.layout.ConversionPattern=%p %t %c - %m%n
#log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n

2) Add the following code to WEB-INF/web.xml
<servlet> 
     <servlet-name>log4j-init</servlet-name>
     <servlet-class>com.AppName.servlets.Log4jInit</servlet-class> 
     <init-param>
       <param-name>log4j-init-file</param-name>
       <param-value>WEB-INF/classes/log4j.properties</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
</servlet>  


3) Add the servlet you mapped in the step 2 Log4jInit
import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;
 
public class Log4jInit extends HttpServlet {
 
 public void init()
 {
     String prefix =  getServletContext().getRealPath("/");
     String file = getInitParameter("log4j-init-file");
  
     // if the log4j-init-file context parameter is not set, then no point in trying
     if(file != null){
      PropertyConfigurator.configure(prefix+file);
      System.out.println("Log4J Logging started: " + prefix+file);
     }
     else{
      System.out.println("Log4J Is not configured for your Application: " + prefix + file);
     }     
 }
}
4) Using logger
private Logger LOG = Logger.getLogger(YourClass.class);
LOG .debug("Some string to print out");

No comments:

Post a Comment