Posts Tagged ‘Servlet’

Configuring logging in a Java web application

Tuesday, December 4th, 2007

Here is a short HOWTO for making some initial configuring when using Commons logging or log4j. Additionally this post will describe how to set the default locale in a servlet environment.

First you will need to create a new class derived from HttpServlet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package mypackage;
 
import java.util.Locale;
 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
 
/**
 * Initializes log4j so it reads its configuration from WEB-INF directory and sets default locale.
 * @author Ralph Schuster
 *
 */
public class LogConfiguratorServlet extends HttpServlet {
 
   /**
    * Serial ID.
    */
   private static final long serialVersionUID = -5756062055681369027L;
 
   private static final String DEFAULT_FILE = "WEB-INF/log4j.properties";
 
   private static final String DEFAULT_LOCALE = "en_US"; // You can use "en", too.
 
   /**
    * Initializes log4j and sets default locale.
    */
   public void init() {
      // Do the log4j configuration
      String prefix =  getServletContext().getRealPath("/");
      String file = getInitParameter("config-file");
      // if the config-file is not set, then no point in trying
      String s = null;
      if (file != null) {
         s = prefix+file;
      } else {
         s = prefix+DEFAULT_FILE;
      }
      PropertyConfigurator.configure(s);
      LogFactory.getLog(getClass()).debug("log4j configuration file: "+s);
 
      // Do the locale configuration
      s = getInitParameter("locale");
      if (s == null) s = DEFAULT_LOCALE;
      Locale available[] = Locale.getAvailableLocales();
      for (int i=0; i<available.length; i++) {
         if (available[i].toString().equals(s)) {
            Locale.setDefault(available[i]);
         }
      }
      LogFactory.getLog(getClass()).debug("Default locale set to: "+Locale.getDefault());
   }
 
   /**
    * Does nothing.
    */
   public void doGet(HttpServletRequest req, HttpServletResponse res) {
   }
 
}

You then need to deploy the class in your servlet container and adjust the web.xml file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   <servlet>
      </servlet-name>log4j-init</servlet-name>
      <servlet-class>mypackage.LogConfiguratorServlet</servlet-class>
 
      <init-param>
         <param-name>config-file</param-name>
         <param-value>WEB-INF/log4j.properties</param-value>
      </init-param>
      <init-param>
         <param-name>locale</param-name>
         <param-value>de_DE</param-value>
      </init-param>
 
      <load-on-startup>1</load-on-startup>
   </servlet>