• MDC的使用(Mapped Diagnostic Context)的使用


    通常我们可能会有大量的任务需要提交提交到线程池执行,但是此时如果不对日志添加唯一标识进行区分的话回到错乱一坨无法进行查看。因此可以对每一天日志添加唯一的标识,例如使用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>
    

      

  • 相关阅读:
    MFC中添加自己定义的消息
    动态创建的list control添加消息响应
    关于CString的奇怪问题
    如何去掉按钮在输入焦点切换时所产生的闪烁
    wince中将自己的应用程序编译到内核并开机启动的一种方法
    wince下圆角矩形按钮的实现
    关于error C2471:无法更新程序数据库的错误的解决方法
    关于烧写开机logo之后导致无法启动系统的问题
    利用IdHTTP进行多线程下载
    TEdit 控件的提示,就像 IE7 的地址输入栏一样
  • 原文地址:https://www.cnblogs.com/leodaxin/p/9663702.html
Copyright © 2020-2023  润新知