对于多线程的程序来说,排错是一件特别麻烦的事情,特别是针对日志,多线程有可能发生日志写阻塞,那我们有没有可能每一个线程一个日志文件呢?答案是可以的,基于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 = {"a","b","c"};
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
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logFileName
logback
<-以logFileName开头的log文件->
${log.path}/${logFileName}.log
%d{yyyy-MM-dd HH:mm:ss.SSS} %mdc [%thread] %-5level %logger{36} - %msg%n
${log.path}/${logFileName}.%d{yyyy-MM-dd}.log
30