---
title: "Spring 源码分析(Log4jConfigListener Parts)"
author: "hotforcc"
date: "2007-08-25T09:21:55Z"
tags: []
categories: ["非技术"]
slug: "spring-log4jconfiglistener-parts"
draft: false
lastmod: "2007-08-25T09:21:55Z"
id: 116598
url: "https://hotforcc.iteye.com/blog/116598"
---

java 代码

 

001. Spring Open Sourse Research(Log4jConfigListener Parts)
002. /\**
003. * Bootstrap listener for custom Log4J initialization in a web environment.
004. * Delegates to Log4jWebConfigurer (see its javadoc for configuration details).
005. \*
006. * WARNING: Assumes an expanded WAR file, both for loading the configuration
007. * file and for writing the log files. If you want to keep your WAR unexpanded or
008. * don't need application-specific log files within the WAR directory, don't use
009. * Log4J setup within the application (thus, don't use Log4jConfigListener or
010. * Log4jConfigServlet). Instead, use a global, VM-wide Log4J setup (for example,
011. * in JBoss) or JDK 1.4's java.util.logging (which is global too).
012. \*
013. \*
014. This listener should be registered before ContextLoaderListener in web.xml,
015. * when using custom Log4J initialization.
016. \*
017. \*
018. For Servlet 2.2 containers and Servlet 2.3 ones that do not
019. * initalize listeners before servlets, use Log4jConfigServlet.
020. * See the ContextLoaderServlet javadoc for details.
021. \*
022. * @author Juergen Hoeller
023. * @since 13.03.2003
024. * @see Log4jWebConfigurer
025. * @see Log4jConfigServlet
026. * @see org.springframework.web.context.ContextLoaderListener
027. * @see org.springframework.web.context.ContextLoaderServlet
028. * @see WebAppRootListener
029. \*/
030. public class Log4jConfigListener implements ServletContextListener {
031. public void contextInitialized(ServletContextEvent event) {
032. Log4jWebConfigurer.initLogging(event.getServletContext());
033. }
034. public void contextDestroyed(ServletContextEvent event) {
035. Log4jWebConfigurer.shutdownLogging(event.getServletContext());
036. }
037. }
038. Log4jWebConfigurer.java
039. public abstract class Log4jWebConfigurer {
040. /\** Parameter specifying the location of the Log4J config file \*/
041. public static final String CONFIG\_LOCATION\_PARAM = "log4jConfigLocation";
042. /\** Parameter specifying the refresh interval for checking the Log4J config file \*/
043. public static final String REFRESH\_INTERVAL\_PARAM = "log4jRefreshInterval";
044. /\** Parameter specifying whether to expose the web app root system property \*/
045. public static final String EXPOSE\_WEB\_APP\_ROOT\_PARAM = "log4jExposeWebAppRoot";
046. /\**
047. * Initialize Log4J, including setting the web app root system property.
048. * @param servletContext the current ServletContext
049. * @see WebUtils#setWebAppRootSystemProperty
050. \*/
051. public static void initLogging(ServletContext servletContext) {
052. // Expose the web app root system property.
053. if (exposeWebAppRoot(servletContext)) {
054. WebUtils.setWebAppRootSystemProperty(servletContext);
055. }
056. // Only perform custom Log4J initialization in case of a config file.
057. //CONFIG\_LOCATION\_PARAM 为log4j.properties的存放路径
058. String location = servletContext.getInitParameter(CONFIG\_LOCATION\_PARAM);
059. if (location != null) {
060. // Perform actual Log4J initialization; else rely on Log4J's default initialization.
061. try {
062. // Return a URL (e.g. "classpath:" or "file:") as-is;
063. // consider a plain file path as relative to the web application root directory.
064. if (!ResourceUtils.isUrl(location)) {
065. // Resolve system property placeholders before resolving real path.
066. location = SystemPropertyUtils.resolvePlaceholders(location);
067. location = WebUtils.getRealPath(servletContext, location);
068. }
069. // Write log message to server log.
070. //初始化log
071. servletContext.log("Initializing Log4J from \[" + location + "]");
072. // Check whether refresh interval was specified.
073. // REFRESH\_INTERVAL\_PARAM equals the refresh interval for checking the Log4J config file
074. String intervalString = servletContext.getInitParameter(REFRESH\_INTERVAL\_PARAM);
075. if (intervalString != null) {
076. // Initialize with refresh interval, i.e. with Log4J's watchdog thread,
077. // checking the file in the background.
078. try {
079. long refreshInterval = Long.parseLong(intervalString);
080. Log4jConfigurer.initLogging(location, refreshInterval);
081. }
082. catch (NumberFormatException ex) {
083. throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());
084. }
085. }
086. else {
087. // Initialize without refresh check, i.e. without Log4J's watchdog thread.
088. Log4jConfigurer.initLogging(location);
089. }
090. }
091. catch (FileNotFoundException ex) {
092. throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
093. }
094. }
095. }
096. /\**
097. * Return whether to expose the web app root system property,
098. * checking the corresponding ServletContext init parameter.
099. * @see #EXPOSE\_WEB\_APP\_ROOT\_PARAM
100. \*/
101. //返回是否暴露web app root system property
102. //get the "log4jExposeWebAppRoot" para from web.xml
103. private static boolean exposeWebAppRoot(ServletContext servletContext) {
104. String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE\_WEB\_APP\_ROOT\_PARAM);
105. return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam).booleanValue());
106. }
107. }
108. WebUtils.java
109. public abstract class WebUtils {
110. /\**
111. * Standard Servlet 2.3+ spec request attributes for include URI and paths.
112. \*
113. If included via a RequestDispatcher, the current resource will see the
114. * originating request. Its own URI and paths are exposed as request attributes.
115. \*/
116. public static final String INCLUDE\_REQUEST\_URI\_ATTRIBUTE = "javax.servlet.include.request\_uri";
117. public static final String INCLUDE\_CONTEXT\_PATH\_ATTRIBUTE = "javax.servlet.include.context\_path";
118. public static final String INCLUDE\_SERVLET\_PATH\_ATTRIBUTE = "javax.servlet.include.servlet\_path";
119. public static final String INCLUDE\_PATH\_INFO\_ATTRIBUTE = "javax.servlet.include.path\_info";
120. public static final String INCLUDE\_QUERY\_STRING\_ATTRIBUTE = "javax.servlet.include.query\_string";
121. /\**
122. * Standard Servlet 2.4+ spec request attributes for forward URI and paths.
123. \*
124. If forwarded to via a RequestDispatcher, the current resource will see its
125. * own URI and paths. The originating URI and paths are exposed as request attributes.
126. \*/
127. public static final String FORWARD\_REQUEST\_URI\_ATTRIBUTE = "javax.servlet.forward.request\_uri";
128. public static final String FORWARD\_CONTEXT\_PATH\_ATTRIBUTE = "javax.servlet.forward.context\_path";
129. public static final String FORWARD\_SERVLET\_PATH\_ATTRIBUTE = "javax.servlet.forward.servlet\_path";
130. public static final String FORWARD\_PATH\_INFO\_ATTRIBUTE = "javax.servlet.forward.path\_info";
131. public static final String FORWARD\_QUERY\_STRING\_ATTRIBUTE = "javax.servlet.forward.query\_string";
132. /\**
133. * Prefix of the charset clause in a content type String: ";charset="
134. \*/
135. public static final String CONTENT\_TYPE\_CHARSET\_PREFIX = ";charset=";
136. /\**
137. * Default character encoding to use when request.getCharacterEncoding
138. * returns null, according to the Servlet spec.
139. * @see ServletRequest#getCharacterEncoding
140. \*/
141. public static final String DEFAULT\_CHARACTER\_ENCODING = "ISO-8859-1";
142. /\**
143. * Standard Servlet spec context attribute that specifies a temporary
144. * directory for the current web application, of type java.io.File.
145. \*/
146. public static final String TEMP\_DIR\_CONTEXT\_ATTRIBUTE = "javax.servlet.context.tempdir";
147. /\**
148. * HTML escape parameter at the servlet context level
149. * (i.e. a context-param in web.xml): "defaultHtmlEscape".
150. \*/
151. public static final String HTML\_ESCAPE\_CONTEXT\_PARAM = "defaultHtmlEscape";
152. /\**
153. * Web app root key parameter at the servlet context level
154. * (i.e. a context-param in web.xml): "webAppRootKey".
155. \*/
156. public static final String WEB\_APP\_ROOT\_KEY\_PARAM = "webAppRootKey";
157. /\** Default web app root key: "webapp.root" \*/
158. public static final String DEFAULT\_WEB\_APP\_ROOT\_KEY = "webapp.root";
159. /\** Name suffixes in case of image buttons \*/
160. public static final String\[] SUBMIT\_IMAGE\_SUFFIXES = {".x", ".y"};
161. /\** Key for the mutex session attribute \*/
162. public static final String SESSION\_MUTEX\_ATTRIBUTE = WebUtils.class.getName() + ".MUTEX";
163. /\**
164. * Set a system property to the web application root directory.
165. * The key of the system property can be defined with the "webAppRootKey"
166. * context-param in web.xml. Default is "webapp.root".
167. \*
168. Can be used for tools that support substition with System.getProperty
169. * values, like Log4J's "${key}" syntax within log file locations.
170. * @param servletContext the servlet context of the web application
171. * @throws IllegalStateException if the system property is already set,
172. * or if the WAR file is not expanded
173. * @see #WEB\_APP\_ROOT\_KEY\_PARAM
174. * @see #DEFAULT\_WEB\_APP\_ROOT\_KEY
175. * @see WebAppRootListener
176. * @see Log4jWebConfigurer
177. \*/
178. /\*\*把当前的项目的路径放到System属性参数中，供以后调用，其中key值为web.xml
179. webAppRootKey
180. fms.root
181. \*/
182. public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
183. Assert.notNull(servletContext, "ServletContext must not be null");
184. String root = servletContext.getRealPath("/");// 项目路径
185. if (root == null) {
186. throw new IllegalStateException(
187. "Cannot set web app root system property when WAR file is not expanded");
188. }
189. String param = servletContext.getInitParameter(WEB\_APP\_ROOT\_KEY\_PARAM);
190. String key = (param != null ? param : DEFAULT\_WEB\_APP\_ROOT\_KEY);
191. String oldValue = System.getProperty(key);
192. if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
193. throw new IllegalStateException(
194. "Web app root system property already set to different value: '" +
195. key + "' = \[" + oldValue + "] instead of \[" + root + "] - " +
196. "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
197. }
198. System.setProperty(key, root);
199. servletContext.log("Set web app root system property: '" + key + "' = \[" + root + "]");
200. }
201. }

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.