1. 程式人生 > >【轉】SLF4J整合log4j

【轉】SLF4J整合log4j

一,引入jar

maven 專案中,只需要引入下面的dependency

<dependency>  
    <groupId>org.slf4j</groupId>  
    <artifactId>slf4j-log4j12</artifactId>  
    <version>1.7.2</version>  
</dependency>

二、配置log4j.properties

因為log4j是具體的實現框架,需要配置log4j.properties

# rootLogger引數分別為:根Logger級別,輸出器stdout,輸出器log
log4j.rootLogger = info,stdout,log

# 輸出資訊到控制檯
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d [%-5p] %l %rms: %m%n

# 輸出DEBUG級別以上的日誌到D://logs/debug.log
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.DatePattern = '.'yyyy-MM-dd
log4j.appender.log.File = D://debug.log
log4j.appender.log.Encoding = UTF-8
#log4j.appender.log.Threshold = INFO
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern = %d [%-5p] (%c.%t): %m%n

三、初始化log4j環境

web環境中,啟動容器時候,就初始化log4j,在web.xml中配置如下:

<!-- 配置log4j配置檔案路徑 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:conf/log4j.properties</param-value>
    </context-param>
    <!-- 60s 檢測日誌配置 檔案變化 -->
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>

    <!-- 配置Log4j監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

四、使用

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    public static void main(String[] args) {
        int status = 0;
        if (status == 0) {
            logger.info("status:{}", status);
        } else {
            logger.info("status:{}", status);
        }
        logger.info("end!");
    }
}

五、總結

如果需要更換專案的SLF4J日誌框架實現,比如logback,不需要修改程式碼,直接更換日誌框架的實現,很方便。

轉載:https://www.cnblogs.com/Jason-Xiang/p/6549608.html