当前位置:网站首页>[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 .
边栏推荐
- How is it that the income of financial products is zero for several consecutive days?
- C#合并多个richtextbox内容时始终存在换行符的解决方法
- FTP_ Manipulate remote files
- AQS - detailed explanation of reentrantlock source code
- 思路清晰的软光栅小引擎和四元数结合案例
- TCP协议的三次握手过程和四次挥手过程以及为什么要这样? ------一二熊猫
- Detailed description of drawing ridge plot, overlapping densities of overlapping kernel density estimation curve, facetgrid object and function sns Kdeplot, function facetgrid map
- Three handshakes and four waves of TCP protocol and why------ One two pandas
- socket编程2:IO复用(select && poll && epoll)
- No configure file found when compiling PHP from source code
猜你喜欢
Tidb data migration (DM) Introduction
Compilation and development process of Quanzhi v3s environment
关于#数据库#的问题:PGADMIN4 编辑sql窗口问题
redis-4. Redis' message subscription, pipeline, transaction, modules, bloom filter, and cache LRU
How idea breaks point debugging
Detailed description of drawing ridge plot, overlapping densities of overlapping kernel density estimation curve, facetgrid object and function sns Kdeplot, function facetgrid map
Implementation of fruit mall wholesale platform based on SSM
Calculate running total / running balance
AQS - detailed explanation of reentrantlock source code
【ViveFocus使用WaveVR插件获取手柄操作事件】
随机推荐
25个国内外文献数据库
socket编程2:IO复用(select && poll && epoll)
AQS - detailed explanation of reentrantlock source code
8. process status and transition
SDN基本概述
Reflection of C # Foundation
Priority analysis of list variables in ansible playbook and how to separate and summarize list variables
考研英语
10. process communication
6. system call
C语言:如何给全局变量起一个别名?
Micro isolation (MSG)
Tree list under winfrom treelist related
Database outline
10 Honest Facts I Want To Share With All Junior Developers
不同系统添加证书
Nfv basic overview
Evolution in the digital age
redis-7. Redis master-slave replication, cap, Paxos, cluster sharding cluster 02
It's called the next generation monitoring system. Let's see how awesome it is