通常我们可能会有大量的任务需要提交提交到线程池执行,但是此时如果不对日志添加唯一标识进行区分的话回到错乱一坨无法进行查看。因此可以对每一天日志添加唯一的标识,例如使用userid作为日志的唯一标志。这样就可以使用MDC实现,MDC其实就是共享线程上下文。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import java.util.Map; import java.util.concurrent.*; import static java.util.concurrent.TimeUnit.SECONDS; public class LogMDC { private static final Logger logger = LoggerFactory.getLogger("logic"); // 使用logic打印线程池执行任务的日志 public static void main(String[] args) { MDC.put("sessionId", "sessionId_Value"); MDC.put("userName", "userName_Value"); ExecutorService executors = Executors.newFixedThreadPool(4); Future<Integer> f = executors.submit(new TaskMDC()); try { System.out.println(f.get(2, SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); logger.error(e.getMessage()); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } // You can put values in the MDC at any time. Before anything else // we put the first name MDC.put("first", "Dorothy"); // We now put the last name MDC.put("last", "Parker"); // The most beautiful two words in the English language according // to Dorothy Parker: logger.info("Check enclosed."); logger.debug("The most beautiful two words in English."); MDC.put("first", "Richard"); MDC.put("last", "Nixon"); logger.info("I am not a crook."); logger.info("Attributed to the former US president. 17 Nov 1973."); } static class TaskMDC implements Callable<Integer> { private Map<String, String> map; public TaskMDC() { this.map = MDC.getCopyOfContextMap(); } @Override public Integer call() throws Exception { if (map != null) { MDC.setContextMap(map); } // The most beautiful two words in the English language according // to Dorothy Parker: logger.info("Call Thread Check enclosed."); logger.debug("Call Thread The most beautiful two words in English."); MDC.put("first", "Richard"); MDC.put("last", "Nixon"); logger.info("Call Thread I am not a crook."); logger.info("Call Thread Attributed to the former US president. 17 Nov 1973."); return 2; } } }
log4j.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="target" value="System.out"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss.SSS} - %X{userName} - %m%n"/> </layout> </appender> <appender name="error" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="./logs/error.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <param name="threshold" value="error"/> <param name="append" value="true"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] - %X{userName} - %m%n"/> </layout> </appender> <appender name="logic" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="./logs/logic.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <param name="threshold" value="info"/> <param name="append" value="true"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] - %X{userName} - %m%n"/> </layout> </appender> <appender name="trace" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="./logs/trace.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <param name="threshold" value="info"/> <param name="append" value="true"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] - %X{userName} - %m%n"/> </layout> </appender> <logger name="traceLog" additivity="false"> <level value="info"/> <appender-ref ref="trace"/> </logger> <root> <level value="info"/> <appender-ref ref="console"/> <appender-ref ref="logic"/> <appender-ref ref="error"/> </root> </log4j:configuration>
pom:
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency>