View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-9-24 下午05:24:19
4    */
5   package gboat2.base.plugin.servlet.listener;
6   
7   import java.io.FileInputStream;
8   import java.io.IOException;
9   import java.util.logging.LogManager;
10  
11  import javax.servlet.ServletContext;
12  import javax.servlet.ServletContextEvent;
13  
14  import org.apache.commons.io.IOUtils;
15  import org.apache.commons.lang3.SystemUtils;
16  import org.springframework.util.Assert;
17  import org.springframework.web.util.Log4jConfigListener;
18  
19  /**
20   * 读取jdk日志配置文件,初始化jdk日志配置,控制使用jdk自带日志的第三方包的日志输出。<br>
21   * 使用方式:<pre>
22   * 1. 在 web.xml 中配置该监听器:
23   *    <code>&lt;listener&gt;
24   *        &lt;listener-class&gt;gboat2.base.plugin.servlet.listener.JDKLoggerConfigListener&lt;/listener-class&gt;
25   *    &lt;/listener&gt;</code>
26   * 2. JUL(Java Util Logging)的日志策略配置文件默认是使用 /WEB-INF/config/logging.properties,可通过在 web.xml 添加如下配置进行修改:
27   *    <code>&lt;context-param&gt;
28   *        &lt;description&gt;java util logging 日志策略配置文件&lt;/description&gt;
29   *        &lt;param-name&gt;jdkLogConfigPathKey&lt;/param-name&gt;
30   *        &lt;param-value&gt;/WEB-INF/config/logging.properties&lt;/param-value&gt;
31   *    &lt;/context-param&gt;
32   * </code></pre>
33   * @date 2013-1-4
34   * @author zhangxj-a
35   * @author <a href="mailto:[email protected]">何明旺</a>
36   * @since 1.0
37   */
38  public class JDKLoggerConfigListener extends Log4jConfigListener {
39  	
40  	public static final String JDK_LOG_CONFIG_KEY_PARM = "jdkLogConfigPathKey";
41  	
42  	public void contextInitialized(ServletContextEvent event) {
43  		super.contextInitialized(event);
44  		setJdkLogConfigPathSystemProperty(event.getServletContext());
45  	}
46  	
47  	private  void setJdkLogConfigPathSystemProperty(ServletContext servletContext) throws IllegalStateException {
48  		Assert.notNull(servletContext, "ServletContext must not be null");
49  		String root = servletContext.getRealPath("/");
50          String param = servletContext.getInitParameter(JDK_LOG_CONFIG_KEY_PARM);
51          param = (param == null) ? "/WEB-INF/config/logging.properties" : param;
52  		
53  		String key = "java.util.logging.config.file";
54  		String value = root + param;
55  		System.setProperty(key, value);
56  		servletContext.log("Set jdk log config path system property: '" + key + "' = [" + value + "]");
57  		
58  //		Reinitialize the logging properties and reread the logging configuration
59  		FileInputStream logStream = null;
60  		try {
61  			logStream = new FileInputStream(value);
62  			LogManager.getLogManager().readConfiguration(logStream);
63  		} catch (IOException e) {
64  			servletContext.log("Use default jdk property file logging.properties in the direcory of: " + SystemUtils.getJavaHome() + "/lib");
65  		} finally {
66  		    IOUtils.closeQuietly(logStream);
67  		}
68  	}
69  }