logback实现每个线程一个独立的日志文件

本文介绍如何使用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信息中。


你可能感兴趣的:(日志)