Logback MDCAdapter日志跟踪及自定义效果源码解读

 更新时间:2023年11月12日 09:02:42   作者:codecraft  
这篇文章主要为大家介绍了Logback MDCAdapter日志跟踪及自定义效果源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下LogbackMDCAdapter

MDCAdapter

org/slf4j/spi/MDCAdapter.java

public interface MDCAdapter {
    /**
     * Put a context value (the <code>val</code> parameter) as identified with
     * the <code>key</code> parameter into the current thread's context map. 
     * The <code>key</code> parameter cannot be null. The <code>val</code> parameter
     * can be null only if the underlying implementation supports it.
     * 
     * <p>If the current thread does not have a context map it is created as a side
     * effect of this call.
     */
    public void put(String key, String val);
    /**
     * Get the context identified by the <code>key</code> parameter.
     * The <code>key</code> parameter cannot be null.
     * 
     * @return the string value identified by the <code>key</code> parameter.
     */
    public String get(String key);
    /**
     * Remove the context identified by the <code>key</code> parameter.
     * The <code>key</code> parameter cannot be null. 
     * 
     * <p>
     * This method does nothing if there is no previous value 
     * associated with <code>key</code>.
     */
    public void remove(String key);
    /**
     * Clear all entries in the MDC.
     */
    public void clear();
    /**
     * Return a copy of the current thread's context map, with keys and 
     * values of type String. Returned value may be null.
     * 
     * @return A copy of the current thread's context map. May be null.
     * @since 1.5.1
     */
    public Map<String, String> getCopyOfContextMap();
    /**
     * Set the current thread's context map by first clearing any existing 
     * map and then copying the map passed as parameter. The context map 
     * parameter must only contain keys and values of type String.
     * 
     * Implementations must support null valued map passed as parameter.
     * 
     * @param contextMap must contain only keys and values of type String
     * 
     * @since 1.5.1
     */
    public void setContextMap(Map<String, String> contextMap);
    /**
     * Push a value into the deque(stack) referenced by 'key'.
     *      
     * @param key identifies the appropriate stack
     * @param value the value to push into the stack
     * @since 2.0.0
     */
    public void pushByKey(String key, String value);
    /**
     * Pop the stack referenced by 'key' and return the value possibly null.
     * 
     * @param key identifies the deque(stack)
     * @return the value just popped. May be null/
     * @since 2.0.0
     */
    public String popByKey(String key);
    /**
     * Returns a copy of the deque(stack) referenced by 'key'. May be null.
     * 
     * @param key identifies the  stack
     * @return copy of stack referenced by 'key'. May be null.
     * 
     * @since 2.0.0
     */
    public Deque<String>  getCopyOfDequeByKey(String key);
    /**
     * Clear the deque(stack) referenced by 'key'. 
     * 
     * @param key identifies the  stack
     * 
     * @since 2.0.0
     */
    public void clearDequeByKey(String key);
}
slf4j定义了MDCAdapter接口,该接口定义了put、get、remove、clear、getCopyOfContextMap、setContextMap、pushByKey、popByKey、getCopyOfDequeByKey、clearDequeByKey方法

LogbackMDCAdapter

ch/qos/logback/classic/util/LogbackMDCAdapter.java

public class LogbackMDCAdapter implements MDCAdapter  {
    // BEWARE: Keys or values placed in a ThreadLocal should not be of a type/class
    // not included in the JDK. See also https://jira.qos.ch/browse/LOGBACK-450
    final ThreadLocal<Map<String, String>> readWriteThreadLocalMap = new ThreadLocal<Map<String, String>>();
    final ThreadLocal<Map<String, String>> readOnlyThreadLocalMap = new ThreadLocal<Map<String, String>>();
    private final ThreadLocalMapOfStacks threadLocalMapOfDeques = new ThreadLocalMapOfStacks();
    //......
}
LogbackMDCAdapter实现了MDCAdapter接口,它基于readWriteThreadLocalMap、readOnlyThreadLocalMap、threadLocalMapOfDeques来实现

readWriteThreadLocalMap

public void put(String key, String val) throws IllegalArgumentException {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Map<String, String> current = readWriteThreadLocalMap.get();
        if (current == null) {
            current = new HashMap<String, String>();
            readWriteThreadLocalMap.set(current);
        }
        current.put(key, val);
        nullifyReadOnlyThreadLocalMap();
    }
    @Override
    public String get(String key) {
        Map<String, String> hashMap = readWriteThreadLocalMap.get();
        if ((hashMap != null) && (key != null)) {
            return hashMap.get(key);
        } else {
            return null;
        }
    }
    @Override
    public void remove(String key) {
        if (key == null) {
            return;
        }
        Map<String, String> current = readWriteThreadLocalMap.get();
        if (current != null) {
            current.remove(key);
            nullifyReadOnlyThreadLocalMap();
        }
    }
    @Override
    public void clear() {
        readWriteThreadLocalMap.set(null);
        nullifyReadOnlyThreadLocalMap();
    }
    private void nullifyReadOnlyThreadLocalMap() {
        readOnlyThreadLocalMap.set(null);
    }  
    public void setContextMap(Map contextMap) {
        if (contextMap != null) {
            readWriteThreadLocalMap.set(new HashMap<String, String>(contextMap));
        } else {
            readWriteThreadLocalMap.set(null);
        }
        nullifyReadOnlyThreadLocalMap();
    }
put、get、remove、clear、setContextMap都是基于readWriteThreadLocalMap,同时修改操作会同时调用nullifyReadOnlyThreadLocalMap,将readOnlyThreadLocalMap设置为null

getCopyOfContextMap

public Map getCopyOfContextMap() {
        Map<String, String> readOnlyMap = getPropertyMap();
        if (readOnlyMap == null) {
            return null;
        } else {
            return new HashMap<String, String>(readOnlyMap);
        }
    }

    public Map<String, String> getPropertyMap() {
        Map<String, String> readOnlyMap = readOnlyThreadLocalMap.get();
        if (readOnlyMap == null) {
            Map<String, String> current = readWriteThreadLocalMap.get();
            if (current != null) {
                final Map<String, String> tempMap = new HashMap<String, String>(current);
                readOnlyMap = Collections.unmodifiableMap(tempMap);
                readOnlyThreadLocalMap.set(readOnlyMap);
            }
        }
        return readOnlyMap;
    }
getCopyOfContextMap方法通过getPropertyMap获取,如果不为null则新创建HashMap返回;getPropertyMap先从readOnlyThreadLocalMap读取,如果readOnlyThreadLocalMap为null则从readWriteThreadLocalMap拷贝一份unmodifiableMap,并设置到readOnlyThreadLocalMap

threadLocalMapOfDeques

@Override
    public void pushByKey(String key, String value) {
        threadLocalMapOfDeques.pushByKey(key, value);
    }
    @Override
    public String popByKey(String key) {
        return threadLocalMapOfDeques.popByKey(key);
    }
    @Override
    public Deque<String> getCopyOfDequeByKey(String key) {
        return threadLocalMapOfDeques.getCopyOfDequeByKey(key);
    }
    @Override
    public void clearDequeByKey(String key) {
        threadLocalMapOfDeques.clearDequeByKey(key);
    }
pushByKey、popByKey、getCopyOfDequeByKey、clearDequeByKey均是基于threadLocalMapOfDeques,它是ThreadLocalMapOfStacks类型

ThreadLocalMapOfStacks

org/slf4j/helpers/ThreadLocalMapOfStacks.java

public class ThreadLocalMapOfStacks {
    // BEWARE: Keys or values placed in a ThreadLocal should not be of a type/class
    // not included in the JDK. See also https://jira.qos.ch/browse/LOGBACK-450
    final ThreadLocal<Map<String, Deque<String>>> tlMapOfStacks = new ThreadLocal<>();
    public void pushByKey(String key, String value) {
        if (key == null)
            return;
        Map<String, Deque<String>> map = tlMapOfStacks.get();
        if (map == null) {
            map = new HashMap<>();
            tlMapOfStacks.set(map);
        }
        Deque<String> deque = map.get(key);
        if (deque == null) {
            deque = new ArrayDeque<>();
        }
        deque.push(value);
        map.put(key, deque);
    }
    public String popByKey(String key) {
        if (key == null)
            return null;
        Map<String, Deque<String>> map = tlMapOfStacks.get();
        if (map == null)
            return null;
        Deque<String> deque = map.get(key);
        if (deque == null)
            return null;
        return deque.pop();
    }
    public Deque<String> getCopyOfDequeByKey(String key) {
        if (key == null)
            return null;
        Map<String, Deque<String>> map = tlMapOfStacks.get();
        if (map == null)
            return null;
        Deque<String> deque = map.get(key);
        if (deque == null)
            return null;
        return new ArrayDeque<String>(deque);
    }
    /**
     * Clear the deque(stack) referenced by 'key'. 
     * 
     * @param key identifies the  stack
     * 
     * @since 2.0.0
     */
    public void clearDequeByKey(String key) {
        if (key == null)
            return;
        Map<String, Deque<String>> map = tlMapOfStacks.get();
        if (map == null)
            return;
        Deque<String> deque = map.get(key);
        if (deque == null)
            return;
        deque.clear();
    }
}
ThreadLocalMapOfStacks是slf4j定义的,基于ThreadLocal<Map<String, Deque<String>>>实现的

小结

slf4j定义了MDCAdapter接口,该接口定义了put、get、remove、clear、getCopyOfContextMap、setContextMap、pushByKey、popByKey、getCopyOfDequeByKey、clearDequeByKey方法;LogbackMDCAdapter实现了MDCAdapter接口,它基于readWriteThreadLocalMap、readOnlyThreadLocalMap、threadLocalMapOfDeques来实现,其中put、get、remove、clear、setContextMap都是基于readWriteThreadLocalMap,pushByKey、popByKey、getCopyOfDequeByKey、clearDequeByKey均是基于threadLocalMapOfDeques。

以上就是Logback MDCAdapter日志跟踪及自定义效果源码解读的详细内容,更多关于Logback MDCAdapter日志跟踪的资料请关注脚本之家其它相关文章!

相关文章

  • Java深入理解代码块的使用细节

    Java深入理解代码块的使用细节

    所谓代码块是指用"{}"括起来的一段代码,根据其位置和声明的不同,可以分为普通代码块、构造块、静态块、和同步代码块。如果在代码块前加上 synchronized关键字,则此代码块就成为同步代码块
    2022-05-05
  • Spring Security OAuth 自定义授权方式实现手机验证码

    Spring Security OAuth 自定义授权方式实现手机验证码

    这篇文章主要介绍了Spring Security OAuth 自定义授权方式实现手机验证码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Springboot集成shiro之登录拦截/权限控制方式

    Springboot集成shiro之登录拦截/权限控制方式

    文章介绍了Shiro框架的的配置和使用,包括添加依赖、配置ShiroConfig、创建realm、配置安全管理器、配置过滤器和权限控制,还介绍了配置ehcache缓存、自定义加密和处理404重定向等问题,总结了Shiro框架中的常用配置和解决常见问题的方法
    2026-05-05
  • Java基本语法小白入门级

    Java基本语法小白入门级

    Java基本语法就是指java中的规则,也是一种语言规则,规范,同时也能让您在后面的学习中避免不必要的一些错误和麻烦,是您学好java必修的第一门课程
    2023-05-05
  • SpringBoot中的自定义FailureAnalyzer详解

    SpringBoot中的自定义FailureAnalyzer详解

    这篇文章主要介绍了SpringBoot中的自定义FailureAnalyzer详解,FailureAnalyzer是一种很好的方式在启动时拦截异常并将其转换为易读的消息,并将其包含在FailureAnalysis中, Spring Boot为应用程序上下文相关异常、JSR-303验证等提供了此类分析器,需要的朋友可以参考下
    2023-12-12
  • 解析Tomcat 6、7在EL表达式解析时存在的一个Bug

    解析Tomcat 6、7在EL表达式解析时存在的一个Bug

    这篇文章主要是对Tomcat 6、7在EL表达式解析时存在的一个Bug进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2013-12-12
  • Spring深入刨析声明式事务

    Spring深入刨析声明式事务

    在spring注解中,使用声明式事务,需要用到两个核心的注解:@Transactional注解和@EnableTransactionManagement注解。将@Transactional注解加在方法上,@EnableTransactionManagement注解加在配置类上
    2022-12-12
  • 解析Idea为什么不推荐使用@Autowired进行Field注入

    解析Idea为什么不推荐使用@Autowired进行Field注入

    这篇文章主要介绍了Idea不推荐使用@Autowired进行Field注入的原因,网上文章大部分都是介绍两者的区别,没有提到为什么,当时想了好久想出了可能的原因,今天来总结一下
    2022-05-05
  • clickhouse 批量插入数据及ClickHouse常用命令详解

    clickhouse 批量插入数据及ClickHouse常用命令详解

    这篇文章主要介绍了clickhouse 批量插入数据及ClickHouse常用命令,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • Java动态规划之编辑距离问题示例代码

    Java动态规划之编辑距离问题示例代码

    这篇文章主要介绍了Java动态规划之编辑距离问题示例代码,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11

最新评论