当前位置:网站首页>[log framework] add user-defined parameters to the MDC implementation log
[log framework] add user-defined parameters to the MDC implementation log
2022-06-13 07:27:00 【Small side good side】
1、MDC
MDC(Mapped Diagnostic Contexts) Map debug context , It is mainly used for log link tracking , Dynamically configure some user-defined information , such as requestId、sessionId wait .MDC The container used supports multi-threaded operations , Meet thread safety .
2、log4j2 Realization
Call in code MDC.put
public class Log4j2Test {
private static final Logger log = LoggerFactory.getLogger(Log4j2Test.class);
public static void main(String[] args) {
log.info("test");
MDC.put("username", "test123");
log.info("hello world");
}
}
log4j2.properties in ,pattern increase [%X{username}]
effect :
3、logback Realization
Again java Call in code MDC.put
public class LogbackTest {
private static final Logger log = LoggerFactory.getLogger(LogbackTest.class);
public static void main(String[] args) {
MDC.put("custom1", "test122");
log.info("logback test1234-----------------------");
}
}
logback.xml Add custom parameters in 
effect :
4、org.slf4j.MDC
org.slf4j.MDC Through interface MDCAdapter To adapt to different logging frameworks ,MDCAdapter Is a singleton object .
Many different implementation classes 
LogbackMDCAdapter: Essentially, ThreadLocal<Map<String, String>>
public class LogbackMDCAdapter implements MDCAdapter {
final ThreadLocal<Map<String, String>> copyOnThreadLocal = new ThreadLocal();
private static final int WRITE_OPERATION = 1;
private static final int MAP_COPY_OPERATION = 2;
final ThreadLocal<Integer> lastOperation = new ThreadLocal();
// ......
public void put(String key, String val) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
} else {
Map<String, String> oldMap = (Map)this.copyOnThreadLocal.get();
Integer lastOp = this.getAndSetLastOperation(1);
if (!this.wasLastOpReadOrNull(lastOp) && oldMap != null) {
oldMap.put(key, val);
} else {
Map<String, String> newMap = this.duplicateAndInsertNewMap(oldMap);
newMap.put(key, val);
}
}
}
// ......
}
Log4jMDCAdapter
public class Log4jMDCAdapter implements MDCAdapter {
public Log4jMDCAdapter() {
}
public void put(String key, String val) {
ThreadContext.put(key, val);
}
// ......
}
ThreadContext

DefaultThreadContextMap: and LogbackMDCAdapter equally , In essence ThreadLocal<Map<String, String>>
5、 Test whether the child parent thread can inherit
MDC Bottom use ThreadLocal Realization , Can achieve thread isolation , Great for C/S、B/S Architecture this scenario of opening a thread for each request to process , The processing of each request is a separate thread . But usually complex business needs to be processed asynchronously , During a request processing , Call other services asynchronously , The log in this asynchronous process can also read the parent thread's MDC Do you ? In fact, the child and parent threads add up to a complete processing flow , We need to read the parent thread's in the seed thread MDC.
With log4j2 For example , First, let's take a look at the new thread directly , Whether the parent thread can be read in the new thread MDC
public class Log4j2Test {
private static final Logger log = LoggerFactory.getLogger(Log4j2Test.class);
public static void main(String[] args) {
log.info("test");
MDC.put("username", "test123");
log.info("hello world");
new Thread(new Runnable() {
public void run() {
log.info("test Runnable");
}
}).start();
}
}
Of course, the results cannot be read across threads username
But since the bottom floor is ThraedLocal, That is, there are ways to use it across threads ,DefaultThreadContextMap Switch in inheritableMap Decide to localMap Can I integrate between child and parent threads 
then resources Add profile in directory log4j2.component.properties
isThreadContextMapInheritable=true
When you run it again, you will find that the child thread has successfully read username.
however logback It seems that no such switch has been found . however logback There is also a way to implement the inheritance of child and parent threads , For example, many call chains java client , Use logback You can also implement the inheritance of child and parent threads , For specific solutions, please refer to zipkin Of java The client .
边栏推荐
猜你喜欢

全志V3S环境编译开发流程

Micro isolation (MSG)

WWDC2022最大的亮点: MetalFX

Powerdispatcher reverse generation of Oracle data model

C language: how to give an alias to a global variable?

微隔离(MSG)

Calculate running total / running balance

Nfv basic overview
![[Markov chain Monte Carlo] Markov chain Monte Carlo method sampling prior distribution](/img/8a/e6423168e110a168bc3cc6407628f6.png)
[Markov chain Monte Carlo] Markov chain Monte Carlo method sampling prior distribution

How worker threads in the thread pool are recycled
随机推荐
Micro isolation (MSG)
汇编语言基础:寄存器和寻址方式
JMeter encryption interface test
不同系统添加证书
c#高級編程-特性篇
Make cer/pfx public and private key certificates and export CFCA application certificates
对绘制丘岭密度图ridge plot的详细说明、重叠核密度估计曲线overlapping densities、FacetGrid对象、函数sns.kdeplot、函数FacetGrid.map
No configure file found when compiling PHP from source code
How worker threads in the thread pool are recycled
Un des backtraders du cadre de quantification lit l'analyseur
10. process communication
Personal JS learning notes
RT-Thread 模拟器 simulator LVGL控件:slider 控件
Login registration
Implementation of fruit mall wholesale platform based on SSM
C Advanced Programming - features
Calculate running total / running balance
P1434 [SHOI2002] 滑雪 (记忆化搜索
SDN basic overview
redis-6. Redis master-slave replication, cap, Paxos, cluster sharding cluster 01