Log4jInitServlet-支持webapp.root变量

       

        这个Log4jInitServlet主要方便之处是设置了系统变量webapp.root,在log4j.properties文件中就可以这样指定log文件路径。使用${webapp.root}表示web应用的根目录。全小写字母。
log4j.appender.FILE.File=${webapp.root}/WEB-INF/testlog4j.log

      参考Spring对log4j的增强,增加webAppRootKey参数,防止多web应用,系统变量重复。


package com.suncode.log4j;

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;

/**
 * A servlet for initializing Log4j. See <a href=
 * "http://jakarta.apache.org/log4j/docs/documentation.html">Log4j documentation</a>
 * for how to use Log4j.
 * <p>
 * can use ${webapp.root} as your web app root in your log4j.property file as
 * follows: log4j.appender.FILE.File=${webapp.root}/WEB-INF/testlog4j.log
 *
 * This servlet is never called by a client, but should be called during web
 * application initialization, i.e. when the servlet engine starts. The
 * following code should be inserted in the web.xml file for the web
 * application:
 * </p>
 * <servlet> <servlet-name>Log4jInit</servlet-name>
 * <servlet-class>com.suncode.log4j.Log4jInitServlet</servlet-class>
 * <load-on-startup>1</load-on-startup>
 * <init-param>
 * <param-name>log4j-configuration</param-name>
 * <param-value>/WEB-INF/log4j.properties</param-value>
 * </init-param>
 * <!--如果有多个web应用,怕webapp.root变量重复,可以在init-param里定义webAppRootKey-->
 * <init-param>
 * <param-name>webAppRootKey</param-name>
 * <param-value>webapp.root</param-value>
 * </init-param>
 * </servlet>
 *
 * 2006-1-9 增加webAppRootKey参数,防止多web应用,系统变量重复.
 */
public class Log4jInitServlet extends HttpServlet {

 private final String WEB_APP_ROOT_DEFAULT = "webapp.root";

 public void init() throws ServletException {
  String prefix = getServletContext().getRealPath("/");
  // System.setProperty("webapp.root", prefix);
  String webAppRootKey = getServletConfig().getInitParameter(
    "webAppRootKey");
  if(webAppRootKey == null || webAppRootKey.length() < 1){
   webAppRootKey = WEB_APP_ROOT_DEFAULT;
  }

  System.setProperty(webAppRootKey, prefix);
 
  String propfile = getServletConfig().getInitParameter(
    "log4j-config-file");
  if (propfile != null) {
   PropertyConfigurator.configure(prefix + propfile);
   System.out.println("Log4J Configured.");
  }
 }

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Method stub generated by Lomboz
 }

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Method stub generated by Lomboz
 }
}

你可能感兴趣的:(log4j,servlet,String,application,import,initialization)