Slf4j MDC机制
发布时间:2023-02-16 13:50:47 所属栏目:Java 来源:互联网
导读:MDC 简介 MDC ( Mapped Diagnostic Contexts ),它是一个线程安全的存放诊断日志的容器。 Logback设计的一个目标之一是对分布式应用系统的审计和调试。在现在的分布式系统中,需要同时处理很多的请求。如何来很好的区分日志到底是那个请求输出的呢?我们可以
} } /** * Clear all entries in the MDC. */ public void clear() { lastOperation.set(WRITE_OPERATION); copyOnThreadLocal.remove(); } /** * Get the context identified by the <code>key</code> parameter. * <p/> */ public String get(String key) { final Map<String,String> map = copyOnThreadLocal.get(); if ((map != null) && (key != null)) { return map.get(key); } else { return null; } } /** * Get the current thread's MDC as a map. This method is intended to be used * internally. */ public Map<String,String> getPropertyMap() { lastOperation.set(MAP_copY_OPERATION); return copyOnThreadLocal.get(); } /** * Returns the keys in the MDC as a {@link Set}. The returned value can be * null. */ public Set<String> getKeys() { Map<String,String> map = getPropertyMap(); if (map != null) { return map.keySet(); } else { return null; } } /** * Return a copy of the current thread's context map. Returned value may be * null. */ public Map<String,String> getcopyOfContextMap() { Map<String,String> hashMap = copyOnThreadLocal.get(); if (hashMap == null) { return null; } else { return new HashMap<String,String>(hashMap); } } public void setContextMap(Map<String,String> contextMap) { lastOperation.set(WRITE_OPERATION); Map<String,String>()); newMap.putAll(contextMap); // the newMap replaces the old one for serialisation's sake copyOnThreadLocal.set(newMap); } } final ThreadLocal<Integer> lastOperation = new ThreadLocal<Integer>(); 通过这段代码,我们可以看到底层最终是使用的是ThreadLocal来做实现。 参考 https://logback.qos.ch/manual/mdc.html https://segmentfault.com/a/1190000008315137#articleHeader12 https://ketao1989.github.io/2015/04/29/LogBack-Implemention-And-Slf4j-Mdc/#%E8%BE%93%E5%87%BA%E6%97%A5%E5%BF%97%E6%A8%A1%E6%9D%BF%E8%A7%A3%E6%9E%90 (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |