spring中使用logback日誌組件替換log4j

logback比log4j的強大之處,請到logback的主頁去看,我就不囉嗦了,你懂、或者不懂,logback就在那裏,無比強大,傲視絕倫。java

複製log4j-over-slf4j.jar,logback-classic.jar,logback-core.jar,jcl-over-slf4j.jar到lib目錄,刪除原有的log4j.jar。web

 

建立一個新類ide

package com.boaotech.util;  
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import ch.qos.logback.classic.LoggerContext;  
import ch.qos.logback.classic.joran.JoranConfigurator;  
import ch.qos.logback.core.joran.spi.JoranException;  
/** 
 * @author Kiven Lee 
 * @version 1.0 
 */  
public class LogbackConfigListener implements ServletContextListener {  
    private static final Logger logger = LoggerFactory.getLogger(LogbackConfigListener.class);  
     
    private static final String CONFIG_LOCATION = "logbackConfigLocation";  
    @Override  
    public void contextInitialized(ServletContextEvent event) {  
        //從web.xml中加載指定文件名的日誌配置文件  
        String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);  
        String fn = event.getServletContext().getRealPath(logbackConfigLocation);  
        try {  
            LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();  
            loggerContext.reset();  
            JoranConfigurator joranConfigurator = new JoranConfigurator();  
            joranConfigurator.setContext(loggerContext);  
            joranConfigurator.doConfigure(fn);  
            logger.debug("loaded slf4j configure file from {}", fn);  
        }  
        catch (JoranException e) {  
            logger.error("can loading slf4j configure file from " + fn, e);  
        }  
    }  
    @Override  
    public void contextDestroyed(ServletContextEvent event) {  
    }  
}

在web.xml中加入debug

<!--初始化日誌配置文件 -->  
 <listener>  
     <listener-class>  
         com.boaotech.util.LogbackConfigListener  
     </listener-class>  
 </listener>  
 <context-param>  
     <param-name>logbackConfigLocation</param-name>  
     <param-value>WEB-INF/logback.xml</param-value>  
 </context-param>

最後,在WEB-INF下新建logback.xml配置,配置請參考logback幫助手冊。日誌

通過這樣的配置後,應用中全部使用log4j,common-logger的jar,都可正常經過logback實現日誌輸出。code

相關文章
相關標籤/搜索