Wednesday, November 30, 2011

Using Log4J in Web Application

Create a log4j.properties in your /classes folder - because only /classes and /lib folders will be in Tomcat ClassPath, the convention is to put all .properties files in /classes

Here is what my log4j.properties looks like:
  log4j.rootLogger=DEBUG, RollFileAppender   

log4j.appender.RollFileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.RollFileAppender.File=${catalina.home}/logs/HelloWorld.log
log4j.appender.RollFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RollFileAppender.layout.ConversionPattern=%p %d %C %L %n %m %n


Remember to specify a log4j dependency in your ivy.xml:
 <ivy-module version="2.0">  
<info organisation="org.confucius" module="helloworld"/>
<dependencies>
<dependency org="javax.servlet" name="servlet-api" rev="2.5"/>
<dependency org="log4j" name="log4j" rev="1.2.16"/>
</dependencies>
</ivy-module>


Run the Ant:resolve target to download log4j.jar if necessary.

Remember to add log4j.jar to Eclipse->Project->Properties->JAVA Build Path->Libraries

Update your HelloWorld.java to use log4j:

  package org.confucius;   

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;

public class HelloWorld extends HttpServlet{
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PropertyConfigurator.configure("log4j.properties");
Logger logger = Logger.getLogger(HelloWorld.class);
logger.debug("Received age check request");

int year = Integer.parseInt(request.getParameter("year"));
if (year > 1995)
response.getWriter().println("You are underage!");
else
response.getWriter().println("You may enter!");
}
}


Now if you build and redeploy HelloWorld.war, and do an age check, you will see a HelloWorld.log file in your tomcat_home/logs folder.

No comments: