`
hotforcc
  • 浏览: 61089 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring 源码分析(Log4jConfigListener Parts)

阅读更多
java 代码
 
  1. Spring Open Sourse Research(Log4jConfigListener Parts)  
  2. /** 
  3.  * Bootstrap listener for custom Log4J initialization in a web environment. 
  4.  * Delegates to Log4jWebConfigurer (see its javadoc for configuration details). 
  5.  * 
  6.  * WARNING: Assumes an expanded WAR file, both for loading the configuration 
  7.  * file and for writing the log files. If you want to keep your WAR unexpanded or 
  8.  * don't need application-specific log files within the WAR directory, don't use 
  9.  * Log4J setup within the application (thus, don't use Log4jConfigListener or 
  10.  * Log4jConfigServlet). Instead, use a global, VM-wide Log4J setup (for example, 
  11.  * in JBoss) or JDK 1.4's java.util.logging (which is global too). 
  12.  * 
  13.  * 
  14.  
  15. This listener should be registered before ContextLoaderListener in web.xml, 
  16.  * when using custom Log4J initialization. 
  17.  * 
  18.  * 
  19.  
  20. For Servlet 2.2 containers and Servlet 2.3 ones that do not 
  21.  * initalize listeners before servlets, use Log4jConfigServlet. 
  22.  * See the ContextLoaderServlet javadoc for details. 
  23.  * 
  24.  * @author Juergen Hoeller 
  25.  * @since 13.03.2003 
  26.  * @see Log4jWebConfigurer 
  27.  * @see Log4jConfigServlet 
  28.  * @see org.springframework.web.context.ContextLoaderListener 
  29.  * @see org.springframework.web.context.ContextLoaderServlet 
  30.  * @see WebAppRootListener 
  31.  */  
  32. public class Log4jConfigListener implements ServletContextListener {  
  33.   
  34.     public void contextInitialized(ServletContextEvent event) {  
  35.         Log4jWebConfigurer.initLogging(event.getServletContext());  
  36.     }  
  37.   
  38.     public void contextDestroyed(ServletContextEvent event) {  
  39.         Log4jWebConfigurer.shutdownLogging(event.getServletContext());  
  40.     }  
  41.   
  42. }  
  43.   
  44.   
  45. Log4jWebConfigurer.java  
  46. public abstract class Log4jWebConfigurer {  
  47.   
  48.     /** Parameter specifying the location of the Log4J config file */  
  49.     public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";  
  50.   
  51.     /** Parameter specifying the refresh interval for checking the Log4J config file */  
  52.     public static final String REFRESH_INTERVAL_PARAM = "log4jRefreshInterval";  
  53.   
  54.     /** Parameter specifying whether to expose the web app root system property */  
  55.     public static final String EXPOSE_WEB_APP_ROOT_PARAM = "log4jExposeWebAppRoot";  
  56.   
  57.   
  58.     /** 
  59.      * Initialize Log4J, including setting the web app root system property. 
  60.      * @param servletContext the current ServletContext 
  61.      * @see WebUtils#setWebAppRootSystemProperty 
  62.      */  
  63.     public static void initLogging(ServletContext servletContext) {  
  64.         // Expose the web app root system property.  
  65.         if (exposeWebAppRoot(servletContext)) {  
  66.             WebUtils.setWebAppRootSystemProperty(servletContext);  
  67.         }  
  68.   
  69.         // Only perform custom Log4J initialization in case of a config file.  
  70.         //CONFIG_LOCATION_PARAM 为log4j.properties的存放路径  
  71.         String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);  
  72.         if (location != null) {  
  73.             // Perform actual Log4J initialization; else rely on Log4J's default initialization.  
  74.             try {  
  75.                 // Return a URL (e.g. "classpath:" or "file:") as-is;  
  76.                 // consider a plain file path as relative to the web application root directory.  
  77.                 if (!ResourceUtils.isUrl(location)) {  
  78.                     // Resolve system property placeholders before resolving real path.  
  79.                     location = SystemPropertyUtils.resolvePlaceholders(location);  
  80.                     location = WebUtils.getRealPath(servletContext, location);  
  81.                 }  
  82.   
  83.                 // Write log message to server log.  
  84.                 //初始化log  
  85.                 servletContext.log("Initializing Log4J from [" + location + "]");  
  86.   
  87.                 // Check whether refresh interval was specified.  
  88.                 // REFRESH_INTERVAL_PARAM equals the refresh interval for checking the Log4J config file  
  89.                 String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);  
  90.                 if (intervalString != null) {  
  91.                     // Initialize with refresh interval, i.e. with Log4J's watchdog thread,  
  92.                     // checking the file in the background.  
  93.                     try {  
  94.                         long refreshInterval = Long.parseLong(intervalString);  
  95.                         Log4jConfigurer.initLogging(location, refreshInterval);  
  96.                     }  
  97.                     catch (NumberFormatException ex) {  
  98.                         throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());  
  99.                     }  
  100.                 }  
  101.                 else {  
  102.                     // Initialize without refresh check, i.e. without Log4J's watchdog thread.  
  103.                     Log4jConfigurer.initLogging(location);  
  104.                 }  
  105.             }  
  106.             catch (FileNotFoundException ex) {  
  107.                 throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());  
  108.             }  
  109.         }  
  110.     }  
  111.   
  112.     /** 
  113.      * Return whether to expose the web app root system property, 
  114.      * checking the corresponding ServletContext init parameter. 
  115.      * @see #EXPOSE_WEB_APP_ROOT_PARAM 
  116.      */  
  117.     //返回是否暴露web app root system property  
  118.     //get the "log4jExposeWebAppRoot" para from web.xml  
  119.     private static boolean exposeWebAppRoot(ServletContext servletContext) {  
  120.         String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);  
  121.         return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam).booleanValue());  
  122.     }  
  123.   
  124. }  
  125. WebUtils.java  
  126.   
  127. public abstract class WebUtils {  
  128.   
  129.     /** 
  130.      * Standard Servlet 2.3+ spec request attributes for include URI and paths. 
  131.      * 
  132.  
  133. If included via a RequestDispatcher, the current resource will see the 
  134.      * originating request. Its own URI and paths are exposed as request attributes. 
  135.      */  
  136.     public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";  
  137.     public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";  
  138.     public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path";  
  139.     public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info";  
  140.     public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string";  
  141.   
  142.     /** 
  143.      * Standard Servlet 2.4+ spec request attributes for forward URI and paths. 
  144.      * 
  145.  
  146. If forwarded to via a RequestDispatcher, the current resource will see its 
  147.      * own URI and paths. The originating URI and paths are exposed as request attributes. 
  148.      */  
  149.     public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";  
  150.     public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";  
  151.     public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";  
  152.     public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";  
  153.     public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";  
  154.   
  155.   
  156.     /** 
  157.      * Prefix of the charset clause in a content type String: ";charset=" 
  158.      */  
  159.     public static final String CONTENT_TYPE_CHARSET_PREFIX = ";charset=";  
  160.   
  161.     /** 
  162.      * Default character encoding to use when request.getCharacterEncoding 
  163.      * returns null, according to the Servlet spec. 
  164.      * @see ServletRequest#getCharacterEncoding 
  165.      */  
  166.     public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";  
  167.   
  168.     /** 
  169.      * Standard Servlet spec context attribute that specifies a temporary 
  170.      * directory for the current web application, of type java.io.File. 
  171.      */  
  172.     public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";  
  173.   
  174.     /** 
  175.      * HTML escape parameter at the servlet context level 
  176.      * (i.e. a context-param in web.xml): "defaultHtmlEscape". 
  177.      */  
  178.     public static final String HTML_ESCAPE_CONTEXT_PARAM = "defaultHtmlEscape";  
  179.   
  180.     /** 
  181.      * Web app root key parameter at the servlet context level 
  182.      * (i.e. a context-param in web.xml): "webAppRootKey". 
  183.      */  
  184.     public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";  
  185.   
  186.     /** Default web app root key: "webapp.root" */  
  187.     public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";  
  188.   
  189.     /** Name suffixes in case of image buttons */  
  190.     public static final String[] SUBMIT_IMAGE_SUFFIXES = {".x"".y"};  
  191.   
  192.     /** Key for the mutex session attribute */  
  193.     public static final String SESSION_MUTEX_ATTRIBUTE = WebUtils.class.getName() + ".MUTEX";  
  194.      
  195.     /** 
  196.      * Set a system property to the web application root directory. 
  197.      * The key of the system property can be defined with the "webAppRootKey" 
  198.      * context-param in web.xml. Default is "webapp.root". 
  199.      * 
  200.  
  201. Can be used for tools that support substition with System.getProperty 
  202.      * values, like Log4J's "${key}" syntax within log file locations. 
  203.      * @param servletContext the servlet context of the web application 
  204.      * @throws IllegalStateException if the system property is already set, 
  205.      * or if the WAR file is not expanded 
  206.      * @see #WEB_APP_ROOT_KEY_PARAM 
  207.      * @see #DEFAULT_WEB_APP_ROOT_KEY 
  208.      * @see WebAppRootListener 
  209.      * @see Log4jWebConfigurer 
  210.      */  
  211.     /**把当前的项目的路径放到System属性参数中,供以后调用,其中key值为web.xml 
  212.         
  213.         webAppRootKey 
  214.         fms.root 
  215.         
  216.     */  
  217.     public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {  
  218.         Assert.notNull(servletContext, "ServletContext must not be null");  
  219.         String root = servletContext.getRealPath("/");// 项目路径  
  220.         if (root == null) {  
  221.             throw new IllegalStateException(  
  222.                 "Cannot set web app root system property when WAR file is not expanded");  
  223.         }  
  224.         String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);  
  225.         String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);  
  226.         String oldValue = System.getProperty(key);  
  227.         if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {  
  228.             throw new IllegalStateException(  
  229.                 "Web app root system property already set to different value: '" +  
  230.                 key + "' = [" + oldValue + "] instead of [" + root + "] - " +  
  231.                 "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");  
  232.         }  
  233.         System.setProperty(key, root);  
  234.         servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");  
  235.     }  
  236. }  


In a word ,if you want to use the Log4jConfigListener ,
there are several context params need to config in web.xml as follows:
1,webAppRootKey,项目名称
2,log4jExposeWebAppRoot, whether to expose the webAppRootKey to  the System,是否将webAppRootKey.value这个属性暴露给System,
也就是否可以用System.getProperty(webAppRootKey.value)获得项目名称
3,log4jRefreshInterval,Parameter specifying the refresh interval for checking the Log4J config file
4,log4jConfigLocation,Parameter specifying the place where you can find log4j.properties.

分享到:
评论

相关推荐

    Spring源码分析.pdf

    Spring 源码分析 Spring 框架是 Java 语言中最流行的开源框架之一,它提供了一个强大且灵活的基础设施来构建企业级应用程序。在 Spring 框架中,IOC 容器扮演着核心角色,本文将深入分析 Spring 源码,了解 IOC ...

    spring源码分析(1-10)

    4. **Spring MVC**:Spring MVC是Spring框架的一部分,用于构建Web应用的模型-视图-控制器架构。DispatcherServlet是核心组件,它负责请求分发。Controller接口定义了处理请求的方法,视图解析器将Model数据渲染成...

    Spring项目中怎么配置log4j

    <listener-class>org.springframework.web.util.Log4jConfigListener ``` 以上就是Spring项目中配置log4j的基本步骤和关键知识点。通过合理配置,我们可以实现日志的高效管理和监控,从而提升开发和运维的效率。

    Spring源码分析.txt

    spring源码分析,百度云视频。链接如果失效了,请私聊我。

    spring5学习笔记

    4. **Spring Boot**:熟悉其自动配置机制,快速创建独立的Spring应用,并了解Spring Initializr的作用。 5. **数据访问**:学习使用JdbcTemplate、JPA或MyBatis进行数据库操作,以及Spring Data的高级特性,如...

    spring源码分析专题学习资源

    spring源码分析专题,源码分析视频,对spring的源码进行分析

    log4j2.xml配置

    spring5取消Log4jConfigListener,运用Log4jServletContextListener代替Log4jConfigListener(log4j2.xml的配置)

    Spring源码分析

    以上只是Spring源码分析的部分内容,实际源码中还包括Spring的其他模块,如Spring Batch(批处理)、Spring Security(安全)、Spring Integration(集成)等。理解并掌握Spring源码,有助于我们更好地利用Spring...

    spring简单注解+log4j记录日志

    综上所述,"spring简单注解+log4j记录日志"这个主题涵盖了Spring框架中的注解使用、Log4j日志系统以及AOP的应用。通过学习这些内容,初学者可以更好地理解和实践Spring框架,同时提高代码的可维护性和调试效率。在...

    spring-boot-starter-log4j2

    《深入理解Spring Boot Starter Log4j2》 在Java开发领域,日志系统扮演着至关重要的角色,它帮助开发者记录程序运行过程中的信息,便于排查问题和优化代码。Spring Boot作为一个快速开发框架,自然也提供了对日志...

    spring整合log4j

    Spring框架作为Java企业级应用开发的首选,而Log4j则是广泛使用的日志记录工具,两者结合可以提供强大的日志管理能力。下面将详细阐述"spring整合log4j"的相关知识点。 首先,Log4j是Apache的一个开源项目,它为...

    spring 源码分析CHM

    摘自javaEye 学习spring 源码的必备资料. 多多下载

    spring源码缺失的jar包

    在Spring框架的开发和学习过程中,源码分析是提升技能的重要环节。然而,有时当我们尝试导入Spring的源码时,可能会遇到编译错误,这通常是因为缺少了必要的依赖jar包。这两个关键的jar包对于理解Spring的工作原理...

    Spring5 源码分析(第 2 版)-某Tom老师

    《Spring5 源码分析(第 2 版)》是某Tom老师精心编写的深度解析文档,旨在帮助读者全面理解Spring5的核心机制和设计理念。Spring作为Java领域最为广泛应用的框架之一,其源码的深入理解对于开发者来说至关重要。这篇...

    Spring MVC 框架 整合log4j

    将Spring MVC与Log4j整合,能够帮助我们在开发过程中更好地监控和记录应用的运行状态。 整合Spring MVC和Log4j的过程主要包括以下几个步骤: 1. **添加依赖**:首先,我们需要在项目的构建文件(如Maven的pom.xml...

    Spring5 源码分析(第 2 版) .zip

    《Spring5 源码分析(第 2 版)》是针对Spring框架第五个主要版本的深度解析著作,由知名讲师倾心打造,旨在帮助读者深入理解Spring框架的内部工作机制,提升对Java企业级应用开发的专业技能。本书涵盖了Spring框架的...

    spring 源码中文注释

    在源码分析的过程中,读者会深入理解Spring的内部工作机制,例如如何解析配置、如何创建bean实例、如何实现AOP代理等。这将有助于开发者编写更高效、更健壮的代码,也能为参与Spring的扩展或定制打下坚实基础。 总...

    spring框架和log4j日志用到的jar包

    使用Spring时,开发者还需要注意与其他Java库的兼容性,例如JDBC驱动、ORM框架(如Hibernate、MyBatis)的jar包,以及用于日志记录的log4j.jar、log4j-api.jar和log4j-core.jar。在实际项目中,这些jar包通常会被...

    spring日志配置为log4j

    总之,将Spring的日志配置为Log4j,涉及到引入Log4j库、编写`log4j.properties`配置文件、以及在Spring配置文件中声明使用Log4j。理解这些步骤和配置项对于优化日志记录,排查问题以及监控系统运行状态至关重要。

    spring log4j 实例

    Spring框架是Java领域广泛使用的轻量级框架,而Log4j则是日志记录领域的经典工具,提供了丰富的日志配置和管理功能。本实例结合Spring和Log4j,将为你提供一个实用的日志解决方案。 首先,我们要理解Spring是如何...

Global site tag (gtag.js) - Google Analytics