logbackはスレッドごとに独立したログファイルを実現する

3769 ワード

この文書では、logbackのMapped Diagnostic Context (MDC)SiftingAppenderの使用方法について説明します.
MDC http://logback.qos.ch/manual/mdc.html
logback 1.1.7

1、logback.xmlプロファイルの例


    

    
        
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        
    

    
    
    
        
            logFileName
            logback
        
        
            
            
                logs/${logFileName}.log
                
                    
                        %d{yyyy-MM-dd HH:mm:ss.SSS} %mdc [%thread] %-5level %logger{36} - %msg%n
                    
                
                
                    logback.log.%i.bak
                    1
                    12
                
                
                    100MB
                
            
        
    

    

    
        
        
    

2.javaスレッドコードの例
ここでは,単純なMDC putとremoveにより,各スレッドlogファイル名の独立を実現する.
package com.yangyi;

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

/**
 * Created by yangjinfeng02 on 2016/6/4.
 */
public class Counter implements Runnable {

    private Logger logger = LoggerFactory.getLogger(Counter.class);

    private String counterName;

    public Counter(String counterName) {
        this.counterName = counterName;
    }

    public void run() {
        MDC.put("logFileName", counterName);
        logger.info("start counter {}", counterName);
        MDC.remove("logFileName");
    }
}
package com.yangyi;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yangjinfeng02 on 2016/6/4.
 */
public class Application {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; ++i) {
            executorService.execute(new Counter(String.valueOf(i)));
        }
        executorService.shutdown();
    }
}

PS: logback MDC , , url、 、host 。, web , session id MDC, session , session log 。