---
title: "如何通过项目配置文件指定Log4J的配置文件"
author: "stamen"
date: "2015-07-28T21:47:31Z"
tags: []
categories: ["研发管理"]
slug: "log4j"
draft: false
lastmod: "2020-07-13T15:36:14Z"
id: 2230983
url: "https://stamen.iteye.com/blog/2230983"
---

**引言**
在[打造易于部署的WEB应用项目 ](http://stamen.iteye.com/blog/2230665l)一文中，我们介绍了如何对WEB项目进行重构，使项目WAR包无状态化，给项目部署升级带来了极大的便利的方法：
   1)首先是将项目配置文件通过JVM系统参数指定，将项目部署文件移出WAR包，使项目WAR包只包含程序，不包含配置信息；
   2)此外，还介绍了在Maven项目中如何通过jetty插件提供JNDI数据源，将数据源配置移出Spring配置文件的方法。
   我们给出的解决办法不但照顾到生产环境项目的可部署性，还兼顾了项目开发环境的可移植性，两者天然统一，真可移为“最佳的项目实践”了 :D  

   但我们还留下了一个未考虑到的重要问题：即如何将项目的日志配置文件（即log4j的配置文件）也移出项目之外？因为，在生产环境下，项目运行性时，我们往往需要对项目的日志行为进行控制：如日志级别、日志文件大小等。

**传统Log4J如何配置呢？**   

   使用Spring框架的Web项目，一般是在web.xml中通过org.springframework.web.util.Log4jConfigListener配置Log4j的，它通过一个
log4jConfigLocation上下文参数指定log4J配置文件的地址，如下所示：

```xml

<context-param>  
    <param-name>log4jConfigLocation</param-name>  
    <param-value>WEB-INF/log4j.properties</param-value>  
</context-param>  
<context-param>  
    <param-name>log4jRefreshInterval</param-name>  
    <param-value>600000</param-value>  
</context-param>  
<listener>  
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
</listener>   

```

   虽然你可以指定一个独立于WAR的外部log4j配置文件（如f:/conf/log4j.properties），但是，这样一来就限制了生产环境时log4j配置文件的路径的自由性，另外，log4j配置文件独立于Web项目，开发环境就麻烦了。
   我们期望的解决方案，是要统一开发环境又生产环境的便捷性，因此我们希望通过一个项目配置文件的属性定义log4j配置文件。如果一来，在开发环境下将项目配置文件的属性指向项目中的log4j配置文件，而生产环境下，则指向一个外部的log4j配置文件。

**最佳实践**  

   为了可以通过项目配置文件的属性指定log4j配置文件，我们需要复写org.springframework.beans.factory.config.PropertiesFactoryBean类，以便在加载属性文件时,通过属性值加载log4j配置文件，初始化Log4J日志引擎。

> 为啥非要找PropertiesFactoryBean开刀呢？因为我们希望尽早初始化log4j引擎，而启动Spring时，加载项目配置文件是第一件来做的事，因此搭这班快车就是再自然不过的了 :D  :D 


**完成任务的人**     
   来看我们如何复写PropertiesFactoryBean类：

```java

package com.xxx.sys;

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.util.Assert;
import org.springframework.util.Log4jConfigurer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * 加载平台属性文件，同时初始化Log4J引擎
 * @author : chenxh
 * @date: 2015/7/28
 */
public class FrameworkPropertiesFactoryBean extends PropertiesFactoryBean {

    private static final String LOG4J_CONF_LOCATION = "log4j.conf.location";

    private static final int REFRESH_INTERVAL_INSECONDS = 5;
    public static final String REFRESH_INTERVAL = "log4j.conf.refreshInterval";

    @Override
    protected Properties createProperties() throws IOException {
        Properties properties = super.createProperties();

        //①通过项目配置文件初始化Log4J引擎配置
        initLog4j(properties);
        return properties;
    }


    private void initLog4j(Properties properties) throws IOException{
        String confLocation = properties.getProperty(LOG4J_CONF_LOCATION);
        Assert.hasText(confLocation,"配置文件未定义："+LOG4J_CONF_LOCATION);
        String refreshInterval = properties.getProperty(REFRESH_INTERVAL);
        long refreshIntervalLong = REFRESH_INTERVAL_INSECONDS;
        if (StringUtils.hasText(refreshInterval)) {
            int value = Integer.parseInt(refreshInterval);
            if (value < 2) {
                value = 2;
            }
            refreshIntervalLong = Integer.parseInt(refreshInterval)*1000L;
        }

        //②初始化Log4J引擎的配置
        Log4jConfigurer.initLogging(confLocation,refreshIntervalLong);
    }
}

```


    使用Spring的org.springframework.util.Log4jConfigurer可轻易初始化Log4J引擎，因为这里我们覆盖PropertiesFactoryBean的createProperties()方法，在加载项目配置文件之后，马上初始化Log4J引擎。

 
**安装它**    
   写好FrameworkPropertiesFactoryBean后，我们就要替换Spring配置文件中关于项目属性文件的初始化内容了：
    将以下片段：

```xml

<bean id="frameworkConf"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>#{systemProperties.FRAMEWORK_CONFFILE_PATH}</value>
                <value>classpath*:conf/frameworkVersion.properties</value>
            </list>
        </property>
    </bean>

```

    替换为：

```xml

<bean id="frameworkConf"
          class="com.hsit.tso.framework.web.sys.FrameworkPropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>#{systemProperties.FRAMEWORK_CONFFILE_PATH}</value>
                <value>classpath*:conf/frameworkVersion.properties</value>
            </list>
        </property>
    </bean>

```

   这样FrameworkPropertiesFactoryBean初始化时，Log4J引擎就初始化就绪了。

**项目配置文件相关属性**  
   我们是通过项目配置文件的log4j.conf.location及log4j.conf.refreshInterval来定义Log4J配置文件路径及更新刷新周期的。在开发环境下，我们可以这样定义：

```xml

#log4j的配置文件路径
#1)文件如果在类路径下,以classpath:为前缀,形如:classpath:conf/log4j.properties
#2)文件如果在文件系统下,则采用文件绝对路径,形如 f:/log4j.properties,/etc/conf/log4j.properties

#①这儿=>开发环境嘛，当然基于类路径了
log4j.conf.location=classpath:conf/log4j.properties
#log4j.conf.location=f:/log4j.properties
#日志配置文件变更扫描刷新周期,单位为秒
log4j.conf.refreshInterval=5

```

   而生产环境下，我们可以这样定义：

```xml

#log4j的配置文件路径
#1)文件如果在类路径下,以classpath:为前缀,形如:classpath:conf/log4j.properties
#2)文件如果在文件系统下,则采用文件绝对路径,形如 f:/log4j.properties,/etc/conf/log4j.properties

#①这儿=>生产环境哦，基于文件系统的路径了
log4j.conf.location=f:/log4j.properties
#log4j.conf.location=f:/log4j.properties
#日志配置文件变更扫描刷新周期,单位为秒
log4j.conf.refreshInterval=5

```


**小结**
  为了方便，在生产环境下，建议将Log4J配置文件log4j.properties和项目配置文件放在同一个目录下，这样要更改项目的配置时，只要在这个目录下找到配置文件更改即可。当然了，在开发环境下，也将两者放在一起管理为好，来看我的项目目录结构：

![](http://dl2.iteye.com/upload/attachment/0110/5377/caf04fba-14ba-37a7-a727-c8666ce3941a.png)
   至此，我们就让WEB项目完全无状态化：项目属性文件，数据源，log4J配置文件都外化管理，项目实施人员升级只管大胆更新WAR包，不想笑都难了。 :D  :D 

以后在此维护新文章：
<https://www.jianshu.com/u/d7f090245ddd>