ITeye博客

Spring 源码分析(Log4jConfigListener Parts)

hotforcc · 2007-08-25 09:21 · spring · 非技术 · Markdown

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. This listener should be registered before ContextLoaderListener in web.xml,
  15. * when using custom Log4J initialization.
  16. *
  17. *
  18. For Servlet 2.2 containers and Servlet 2.3 ones that do not
  19. * initalize listeners before servlets, use Log4jConfigServlet.
  20. * See the ContextLoaderServlet javadoc for details.
  21. *
  22. * @author Juergen Hoeller
  23. * @since 13.03.2003
  24. * @see Log4jWebConfigurer
  25. * @see Log4jConfigServlet
  26. * @see org.springframework.web.context.ContextLoaderListener
  27. * @see org.springframework.web.context.ContextLoaderServlet
  28. * @see WebAppRootListener
  29. */
  30. public class Log4jConfigListener implements ServletContextListener {
  31. public void contextInitialized(ServletContextEvent event) {
  32. Log4jWebConfigurer.initLogging(event.getServletContext());
  33. }
  34. public void contextDestroyed(ServletContextEvent event) {
  35. Log4jWebConfigurer.shutdownLogging(event.getServletContext());
  36. }
  37. }
  38. Log4jWebConfigurer.java
  39. public abstract class Log4jWebConfigurer {
  40. /** Parameter specifying the location of the Log4J config file */
  41. public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";
  42. /** Parameter specifying the refresh interval for checking the Log4J config file */
  43. public static final String REFRESH_INTERVAL_PARAM = "log4jRefreshInterval";
  44. /** Parameter specifying whether to expose the web app root system property */
  45. public static final String EXPOSE_WEB_APP_ROOT_PARAM = "log4jExposeWebAppRoot";
  46. /**
  47. * Initialize Log4J, including setting the web app root system property.
  48. * @param servletContext the current ServletContext
  49. * @see WebUtils#setWebAppRootSystemProperty
  50. */
  51. public static void initLogging(ServletContext servletContext) {
  52. // Expose the web app root system property.
  53. if (exposeWebAppRoot(servletContext)) {
  54. WebUtils.setWebAppRootSystemProperty(servletContext);
  55. }
  56. // Only perform custom Log4J initialization in case of a config file.
  57. //CONFIG_LOCATION_PARAM 为log4j.properties的存放路径
  58. String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
  59. if (location != null) {
  60. // Perform actual Log4J initialization; else rely on Log4J's default initialization.
  61. try {
  62. // Return a URL (e.g. "classpath:" or "file:") as-is;
  63. // consider a plain file path as relative to the web application root directory.
  64. if (!ResourceUtils.isUrl(location)) {
  65. // Resolve system property placeholders before resolving real path.
  66. location = SystemPropertyUtils.resolvePlaceholders(location);
  67. location = WebUtils.getRealPath(servletContext, location);
  68. }
  69. // Write log message to server log.
  70. //初始化log
  71. servletContext.log("Initializing Log4J from [" + location + "]");
  72. // Check whether refresh interval was specified.
  73. // REFRESH_INTERVAL_PARAM equals the refresh interval for checking the Log4J config file
  74. String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);
  75. if (intervalString != null) {
  76. // Initialize with refresh interval, i.e. with Log4J's watchdog thread,
  77. // checking the file in the background.
  78. try {
  79. long refreshInterval = Long.parseLong(intervalString);
  80. Log4jConfigurer.initLogging(location, refreshInterval);
  81. }
  82. catch (NumberFormatException ex) {
  83. throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());
  84. }
  85. }
  86. else {
  87. // Initialize without refresh check, i.e. without Log4J's watchdog thread.
  88. Log4jConfigurer.initLogging(location);
  89. }
  90. }
  91. catch (FileNotFoundException ex) {
  92. throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
  93. }
  94. }
  95. }
  96. /**
  97. * Return whether to expose the web app root system property,
  98. * checking the corresponding ServletContext init parameter.
  99. * @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.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。