log4j 结合 spring 配置加载机制


最近经常使用org.slf4j.Logger , 突然间发现log也有很多细活去考虑。这算是一篇浅显的入门配置吧。


web项目下的话,首先位于web-app/WEB-INF/web.xml 这个大家都很熟悉了吧~ 里面的配置如下

    <context-param>
        <param-name><span style="color:#3366ff;background-color: rgb(204, 204, 204);">log4jConfigLocation</span></param-name>
        <param-value>/WEB-INF/conf/log4j.xml</param-value>
    </context-param>

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

一看到上面 , 肯定就是通过这个加载的啦,首先设置环境变量log4jConfigLocation=/WEB-INF/conf/log4j.xml 然后后面的Log4jConfigListener去读取加载这个配置。


Log4jConfigListener代码如下:

public class Log4jConfigListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent event) {
		Log4jWebConfigurer.initLogging(event.getServletContext());
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		Log4jWebConfigurer.shutdownLogging(event.getServletContext());
	}
}

那么肯定是 Log4jWebConfigurer.initLogging(event.getServletContext());  这个读取的喽

跟进这个方法之后我们发现该方法中经过一系列的读取配置文件地址最后执行下面的方法

Log4jConfigurer.initLogging(location);


理解以下上下文,那么肯定就是首先拿到环境变量log4jConfigLocation=/WEB-INF/conf/log4j.xml 然后去读取配置文件啦,所以最核心的方法为Log4jConfigurer.initLogging(location);  所以即使不是web工程(例如thrift)直接去使用以下spring 配置即可直接加log4j的配置

<bean id="log4jInitializer" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass"
                  value="org.springframework.util.Log4jConfigurer" />
        <property name="targetMethod" value="initLogging" />
        <property name="arguments">
            <list>
                <value>classpath:conf/log4j.xml</value>
            </list>
        </property>
    </bean>

OK ,以上就是简单的配置文件喽.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值