1. 程式人生 > >基於slf4j實現多執行緒日誌

基於slf4j實現多執行緒日誌

對於多執行緒的程式來說,排錯是一件特別麻煩的事情,特別是針對日誌,多執行緒有可能發生日誌寫阻塞,那我們有沒有可能每一個執行緒一個日誌檔案呢?答案是可以的,基於slf4j的MDC,具體MDC原理各位看官自行百度

直接上程式碼

/**
 * Created by shengjk1 on 2017/11/30
 */
public class Main {
    protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        String[] destinations = ConfigManager.build().getProperty("destination"
).split(",",-1); logger.info("開始啟動 "); Thread thread=null; for (final String destination:destinations ) { thread=new Thread(new Runnable() { @Override public void run() { MDC.put("logFileName", destination); ClusterCanalClient.run(destination); MDC.remove("logFileName"
); } }); thread.setName(destination); thread.start(); } } }

logback.xml

<?xml version="1.0" encoding="UTF-8" ?>
<configuration scanPeriod="30 seconds" debug="false">
    <jmxConfigurator/>

    <property name="log.path"
value="/home/shengjk1/canaljar/logs/data_exchange" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </layout> </appender> <!-- This is MDC value --> <!-- We will assign a value to 'logFileName' via Java code --> <appender name="FILE-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender"> <discriminator> <key>logFileName</key> <defaultValue>logback</defaultValue> </discriminator> <sift> <!-- A standard RollingFileAppender, the log file is based on 'logFileName' at runtime --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <-以logFileName開頭的log檔案-> <file>${log.path}/${logFileName}.log</file> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <Pattern> %d{yyyy-MM-dd HH:mm:ss.SSS} %mdc [%thread] %-5level %logger{36} - %msg%n </Pattern> </encoder> <!--&lt;!&ndash;按照檔案大小進行滾動&ndash;&gt;--> <!--<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">--> <!--<FileNamePattern>logback.log.%i.bak</FileNamePattern>--> <!--<MinIndex>1</MinIndex>--> <!--<MaxIndex>12</MaxIndex>--> <!--</rollingPolicy>--> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日誌檔案輸出的檔名--> <FileNamePattern>${log.path}/${logFileName}.%d{yyyy-MM-dd}.log</FileNamePattern> <!--日誌檔案保留天數--> <MaxHistory>30</MaxHistory> </rollingPolicy> <!--<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">--> <!--<MaxFileSize>100MB</MaxFileSize>--> <!--</triggeringPolicy>--> </appender> </sift> </appender> <root level="INFO"> <appender-ref ref="STDOUT"/> <appender-ref ref="FILE-THREAD"/> </root> </configuration>