Log4J文件的加载

第一种在 spring 的配置文件中进行加载:

<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:log4j.properties</value>  
            </list>  
        </property>  
    </bean> 

第二种代码编写:

public class Log4jInit implements ServletContextListener{

    Logger log = Logger.getLogger(Log4jInit.class);

    public void contextDestroyed(ServletContextEvent sce) {
        log.info("Log4jInit contextDestroyed!");
    }

    public void contextInitialized(ServletContextEvent sce) {

        //得到servletContext对象的方法
        ServletContext sc = sce.getServletContext();
        //指明文件的相对路径就能够得到文件的绝对路径
        System.out.println(sc.getRealPath("/"));
        String path = sc.getRealPath("/config/log4j.properties");

        //启动服务器的时候加载日志的配置文件
        init(path,sc);
        log.info("log4j");
    }


    /**
     * 
     * @param path 配置文件的路径
     * @param sc ServletContext对象
     */
    public void init(String path,ServletContext sc){
        FileInputStream istream = null;
        try{
            Properties props = new Properties();
            //加载配置文件
            istream = new FileInputStream(path);
            props.remove("log4j.appender.file.File");
            System.out.println(sc.getRealPath("/log/hb.log"));
            //指明log文件的位置
            props.put("log4j.appender.file.File", sc.getRealPath("/log/hb.log"));
            //加载文件流,加载Log4j文件的配置文件信息
            props.load(istream);
            PropertyConfigurator.configure(props);
        } catch (Exception ex){
            try {
                throw new Exception(ex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally{
            try {
                istream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}

第三种web项目工程可以在web.xml中进行配置加载:

<context-param>  
    <param-name>log4jConfigLocation</param-name>  
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param> 

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

记得配置监听器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值