`
seandeng888
  • 浏览: 155002 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

源码赏析之spring对log4j的锦上添花

阅读更多

Log4j在系统记录日志方面功能很强大,但是,在配置文件路径、日志文件路径及动态修改日志记录器级别等信息时却不够灵活,存在一些不足之处。好在spring提供了相关功能弥补了log4j在这方面的不足。接下来就来看一看spring是如何实现这方面功能

spring针对log4j提供了如下功能 
     1. 可以通过定期检查配置文件的变化来动态的改变记录级别和策略,不需要重启Web应用。 web.xml配置如下:

<context-param>   

      <param-name>log4jRefreshInterval</param-name>   

      <param-value>6000</param-value>   

</context-param> 
     2. 日志文件定在 web应用目录下的任何位置,而不需要写绝对路径。 
因为系统把web应用目录的路径压入一个叫webapp.root的系统变量。这样写log文件路径时不用写绝对路径了。当然也可以手动修改该系统变量。web.xml配置如下:

<context-param>

        <param-name>webAppRootKey</param-name>

        <param-value>muse.root</param-value>

</context-param>

注意:不同的应用不可以配置一样的webAppRootKey值,否则会导致系统无法正常启动。

log4j配置如下:log4j.appender.ROLLING_FILE.File=${muse.root}/WEB-INF/logs/muse.log 
   3. 可以把log4j.properties和其他properties一起放在/WEB-INF/ ,而不是Class-Path web.xml配置如下:

<context-param>

        <param-name>log4jConfigLocation</param-name>

        <param-value>/WEB-INF/log4j.xml</param-value>

</context-param>

注:如果要使webAppRootKey生效,则该项一定要配置,当然也可指定properties文件,因为如果没有配置的话,Log4jConfigListener是不会调用log4j初始化配置的。

接下来通过应用配置及源码赏析两方面来详细了解一下这些功能。

应用配置

1.1 web.xml

    所有相关的web.xml配置信息如下:

<context-param>

    <param-name>webAppRootKey</param-name>

    <param-value>muse.root</param-value>

</context-param>

<context-param>

    <param-name>log4jConfigLocation</param-name>

    <param-value>/WEB-INF/log4j.xml</param-value>

</context-param>  

<context-param>   

      <param-name>log4jRefreshInterval</param-name>   

      <param-value>6000</param-value>   

  </context-param>   

  

<listener>   

   <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>  

1.2 log4j.properties配置

    所有相关的log4j.properties配置信息如下:

log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender

log4j.appender.ROLLING_FILE.Threshold=INFO

log4j.appender.ROLLING_FILE.File=${muse.root}/logs/muse.log

log4j.appender.ROLLING_FILE.Append=true

log4j.appender.ROLLING_FILE.MaxFileSize=5000KB

log4j.appender.ROLLING_FILE.MaxBackupIndex=100

log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout

log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n 

源码赏析

2.1 Log4jConfigListener

    这是应用启动时即调用的监听类。该类不具体处理业务逻辑,直接调用Log4jWebConfigurer.initLogging()

public class Log4jConfigListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {

Log4jWebConfigurer.initLogging(event.getServletContext());

}

}

2.2 Log4jWebConfigurer

    这是一个便于在web环境定制log4j初始化的类。即log4j初始化前需要做的一些事情的处理类,当然它也包括调用处理具体初始化工作的类。

public abstract class Log4jWebConfigurer {

/** 该属性用来指定log4j 配置文件的路径。 */

public static final String CONFIG_LOCATION_PARAM = "log4jConfigLocation";

/** 该属性用来指定检查log4j 配置文件的间隔时间。 */

public static final String REFRESH_INTERVAL_PARAM = "log4jRefreshInterval";

/** 该属性用来指定是否设置web应用根目录环境变量。 */

public static final String EXPOSE_WEB_APP_ROOT_PARAM = "log4jExposeWebAppRoot";

/**

 * 初始化log4j,包括设置web应用根目录系统属性。

 */

public static void initLogging(ServletContext servletContext) {

if (exposeWebAppRoot(servletContext)) {

WebUtils.setWebAppRootSystemProperty(servletContext);

}

String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);

if (location != null) {

try {

if (!ResourceUtils.isUrl(location)) {

// 解决系统属性占位符的问题。

location = SystemPropertyUtils.resolvePlaceholders(location);

location = WebUtils.getRealPath(servletContext, location);

}

servletContext.log("Initializing log4j from [" + location + "]");

String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);

if (intervalString != null) {

try {

long refreshInterval = Long.parseLong(intervalString);

Log4jConfigurer.initLogging(location, refreshInterval);

}

catch (NumberFormatException ex) {

throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());

}

}

else {

Log4jConfigurer.initLogging(location);

}

}

catch (FileNotFoundException ex) {

throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());

}

}

}

/**

 * 返回是否进行web应用根目录系统属性设置。

 */

private static boolean exposeWebAppRoot(ServletContext servletContext) {

String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);

return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam));

}

}

2.3 WebUtils

    这个类是web应用程序的五花八门的工具箱。比如设置web应用目录系统属性等。

public abstract class WebUtils {

public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";

/** Default web app root key: "webapp.root" */

public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";

/**

 * 添加一个系统属性用于保存web应用根目录信息。系统属性键可以在web.xml文件的context-param节点定义。默认值为webapp.root

 * 如果不同的应用使用相同的该系统属性键则会报错。

 */

public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {

Assert.notNull(servletContext, "ServletContext must not be null");

String root = servletContext.getRealPath("/");

if (root == null) {

throw new IllegalStateException(

    "Cannot set web app root system property when WAR file is not expanded");

}

String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);

String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);

String oldValue = System.getProperty(key);

if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {

throw new IllegalStateException(

    "Web app root system property already set to different value: '" +

    key + "' = [" + oldValue + "] instead of [" + root + "] - " +

    "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");

}

System.setProperty(key, root);

servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");

}

 

/**

 * 根据相对路径得到web应用下的绝对路径

 */

public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {

Assert.notNull(servletContext, "ServletContext must not be null");

if (!path.startsWith("/")) {

path = "/" + path;

}

String realPath = servletContext.getRealPath(path);

if (realPath == null) {

throw new FileNotFoundException(

"ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +

"web application archive not expanded?");

}

return realPath;

}

}

2.4 Log4jConfigurer

    这是一个具体实现log4j配置的类。该类直接调用log4j组件的相关类进行日志记录器的配置。

public abstract class Log4jConfigurer {

public static final String CLASSPATH_URL_PREFIX = "classpath:";

public static final String XML_FILE_EXTENSION = ".xml";

/**

 * 从指定的配置文件路径来初始化log4j,该方法不支持定时检查配置文件变更功能。

 */

public static void initLogging(String location) throws FileNotFoundException {

String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);

URL url = ResourceUtils.getURL(resolvedLocation);

if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {

DOMConfigurator.configure(url);

}

else {

PropertyConfigurator.configure(url);

}

}

/**

 * 从指定的配置文件路径来初始化log4j,该方法支持定时检查配置文件变更功能。

 */

public static void initLogging(String location, long refreshInterval) throws FileNotFoundException {

String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);

File file = ResourceUtils.getFile(resolvedLocation);

if (!file.exists()) {

throw new FileNotFoundException("Log4j config file [" + resolvedLocation + "] not found");

}

if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {

DOMConfigurator.configureAndWatch(file.getAbsolutePath(), refreshInterval);

}

else {

PropertyConfigurator.configureAndWatch(file.getAbsolutePath(), refreshInterval);

}

}

}

2.5 ResourceUtils

   这是一个用来解决文件资源定位的工具类。

public abstract class ResourceUtils {

public static final String CLASSPATH_URL_PREFIX = "classpath:";

/**

 * 返回指定的资源定位字符串是否是一个URL

 */

public static boolean isUrl(String resourceLocation) {

if (resourceLocation == null) {

return false;

}

if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {

return true;

}

try {

new URL(resourceLocation);

return true;

}

catch (MalformedURLException ex) {

return false;

}

}

}

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics