logback插件的使用

每個工程一個log文件,使用logback實現。


一,jar依賴

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>


<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>1.2.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-access -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-access</artifactId>
    <version>1.2.3</version>
</dependency>

二,logback.xml文件,放在resource下

<configuration>
    <!-- 控制檯 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoder 默認配置爲PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">
        <!-- 定義變量 -->
        <discriminator>
            <Key>fileLogPath</Key>
            <DefaultValue>/</DefaultValue>
        </discriminator>
        <sift>
            <!-- 動態生成文件 -->
            <appender name="FILE-{fileLogPath}" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <File>${fileLogPath}</File>
                <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
                    <FileNamePattern>${fileLogPath}.%i</FileNamePattern>
                    <MinIndex>1</MinIndex>
                    <MaxIndex>100</MaxIndex>
                </rollingPolicy>
                <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
                    <MaxFileSize>50MB</MaxFileSize>
                </triggeringPolicy>
                <layout class="ch.qos.logback.classic.PatternLayout">
                    <Pattern>%d{ISO8601} %-5level %C{1} [%M:%L] [%thread] - %msg%n</Pattern>
                </layout>
            </appender>
        </sift>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

三,java變量
//此處的變量名和xml保持一致
private final static String FILE_LOG_PATH_KEY = "fileLogPath";

public static void error(Logger logger,String logFilePath,String info,Throwable throwable){
    MDC.put(FILE_LOG_PATH_KEY,logFilePath);
    logger.error(info,throwable);
    MDC.remove(MDC.get(FILE_LOG_PATH_KEY));
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章