Logging Filter Example code. Capture logs using Java Servlet logging API.

Log capturing is very important for any application including web applications. The main goal of Logging is to help for debugging the application.

In this section, let us see , how to capture logs using Servlet logging API with the help of Servlet filters (Logging Filters). As we know, one of the main use of Servlet Filters is Logging. For more on Servlet Filters, you can visit my ealier post on Sevlet Filters for Login

Logging can be done by the following APIs

1. Java logging API — java.util.logging / JULI Own implementation of Apache Tomecat based on Java logging API

2. Servlet logging API (javax.servlet.ServletContext.log(…))

3. Any logging frameworks like Log4j

In this post, let us see that how to create Logging Filter using Servlet logging API (javax.servlet.ServletContext.log(…)). Servlet logging API is simple and does not provide much options like controlling log levels. The LogFilter code captures the ip address and access url of a user. The calls to javax.servlet.ServletContext.log(…) writes log messages to the log file. The name and type of the servlet log file is specific to the servlet container. The log() method has two forms which are as follows

public void log(java.lang.String msg) – to write the specified message to a servlet log file, usually an event log.

public void log(java.lang.String message, java.lang.Throwable throwable) – to write a stack trace of throwable exception with description of the error to the servlet log file.

The code for LogFilter is class as follows.

Create a LogFilter class which implements Filter in your application as given below

package Filters;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LogFilter implements Filter {
 private FilterConfig config;
   	public LogFilter() {
   }

   public void init(FilterConfig filterConfig) throws ServletException {
	   this.config = filterConfig;
	   config.getServletContext().log("Logs capturing started");
   }

   public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws java.io.IOException, ServletException {
	   HttpServletRequest req = null;
       req = (HttpServletRequest) request;
       config.getServletContext().log("Request received from: "  + req.getRemoteHost() + " for " + req.getRequestURL());
       readFile();
       chain.doFilter(request, response);
   }

   private void readFile() {
        BufferedReader in;
        String filename="d:\\test.xml";
        try {
             in = new BufferedReader( new FileReader(filename));
        }
        catch (Throwable err) {
        	config.getServletContext().log("Error thrown by readFile method",err);  // captures error.
        }
   }

   public void destroy() {
   }
 }

Now configure the LogFilter class in the Web.xml

 <filter>
 	<filter-name>LogFilter</filter-name>
 	<filter-class>Filters.LogFilter</filter-class>
 </filter>
 <filter-mapping>
 	<filter-name>LogFilter</filter-name>
 	<url-pattern>/*</url-pattern>
  </filter-mapping>

If any user access any of the pages of the application, log are captured into the log file .

If you use eclipse IDE for development, to set the log file location for capturing logs during testing, do the following

Double click on the Apache Tomcat server .

apache server

Now you will get the following screen ,

apache server launch config

In that select open launch configuration and select common tab. Then select File check box , then select the log file location and file name using by selecting the file system as given below.

apache server launch config1

The above code captures, the user client ip address and the url accessed with access date and time. The code calls the function readFile(), the error (in our example, File not found) generated by the readFile() function is also captured in the log file which can be used for debugging.

When the server is started, Logs capture is started

When we call the, http://localhost:8080/TestWeb/login.jsp, the following logs (partly) are generated in the console. Also the same log is captured in the file c:\temp\server.log

logs generated

To capture log using HttpServletRequest either in action or httpservlet, you can call the log method as follows

request.getSession().getServletContext().log(“message”); ,

In the JSP, you call the log() method, by config.getServletContext().log(“message”);

You may also like

Leave a Reply

Be the First to Comment!