当前位置:网站首页>Log4j2 threadcontext log link tracking
Log4j2 threadcontext log link tracking
2022-07-01 01:39:00 【Melting pole】
summary
Log4j2 ThreadContext Allows you to mark log statements with multiple unique tags , In order to analyze logs when diagnosing problems at run time - Mainly in multithreaded applications , The application generates a large number of log records in a short time . for example , You may want to scan all logs for a specific user transaction or full session . This process is also known as fish marking ( That is, add some additional context information in each log statement ). This fish marker can help you use Splunk And so on .
Let's see how we can log4j2 Use in ThreadContextclass Fish marking .
stay ThreadContext Add context information to
To uniquely mark each request , please ThreadContext Provide put(String key, String value) The method of accepting the key and its value . You can add as many tags as you need to capture the entire context . Please note that ,ThreadContext All methods of this class are static .
package com.howtodoinjava.log4j2.examples;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
public class Log4j2HelloWorldExample
{
private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample.class.getName());
public static void main(String[] args)
{
//Add context information
ThreadContext.put("id", UUID.randomUUID().toString());
ThreadContext.put("ipAddress", "192.168.21.9");
LOGGER.debug("Debug Message Logged !!");
LOGGER.info("Info Message Logged !!");
LOGGER.debug("Another Debug Message !!");
//Clear the map
ThreadContext.clearMap();
LOGGER.debug("Thread Context Cleaned up !!");
LOGGER.debug("Log message with no context information !!");
}
}
Or you can put ThreadContext Of Stack Realization and ThreadContext.push(String value) Use it together , As shown below :
//Add context information
ThreadContext.push(UUID.randomUUID().toString());
ThreadContext.push("192.168.21.9");
LOGGER.debug("Debug Message Logged !!");
LOGGER.info("Info Message Logged !!");
LOGGER.debug("Another Debug Message !!");
//Clear the map
ThreadContext.clearStack();
LOGGER.debug("Thread Context Cleaned up !!");
LOGGER.debug("Log message with no context information !!");
After the transaction ends or context information is no longer required , You can use ThreadContext.clearMap() Method clear information .
ThreadContext Of Stack and Map It is managed by thread ThreadLocal. By way of system Property settings isThreadContextMapInheritable by true, Pass the content of the context mapping to the child thread .
modify log4j2.xml Conversion mode in
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%X{id}] [%X{ipAddress}] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>
- Use alone %X contain ThreadContext Everything added .
- Use %X{key} Include the specified key .
- Use %x Include the entire contents of the stack .
Log print results
Now when you run the above code - You will get the following output :
[DEBUG] 2016-06-21 13:09:56.485 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Debug Message Logged !!
[INFO ] 2016-06-21 13:09:56.487 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Info Message Logged !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [7cdd4cf0-2c26-4b81-b374-1adce3781499] [192.168.21.9] Log4j2HelloWorldExample - Another Debug Message !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [] [] Log4j2HelloWorldExample - Thread Context Cleaned up !!
[DEBUG] 2016-06-21 13:09:56.487 [main] [] [] Log4j2HelloWorldExample - Log message with no context information !!
As you can see , Context information has been added to the first three log statements - The other two statements have no such information .
Reference resources
边栏推荐
- Gin configuration file
- 尝试新的可能
- MFC TCP通信服务端客户端Demo备忘vs2019
- 【栈】921. Minimum Add to Make Parentheses Valid
- 6月第4周榜单丨飞瓜数据UP主成长排行榜(哔哩哔哩平台)发布!
- [simulation] 922 Sort Array By Parity II
- Creating ASCII art with C #
- WIN11中MathType编辑中“打开数学输入面板”是灰色不可编辑
- Neo4j installation, operation, project construction and function realization
- The argument type 'function' can't be assigned to the parameter type 'void function()‘
猜你喜欢

使用 C# 创造 ASCII 艺术

一站式洞察行业热点,飞瓜数据B站新功能「流量大盘」上线!

gin_ gorm

Using recyclerreview to show banner is very simple

zabbix如何配置告警短信?(预警短信通知设置流程)

日志 logrus第三方库的使用

【qt5-tab标签精讲】Tab标签及内容分层解析

Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base

工作八年的程序员,却拿着毕业三年的工资,再不开窍就真晚了...

Qt5 mvc: revealing the secrets of data visualization
随机推荐
Why build a personal blog
visual studio 2019 下载
[queue] 933 Number of Recent Calls
System settings large page
物业怎么发短信通知给业主?
微生物安全与健康,什么是生物处理?
"Open math input panel" in MathType editing in win11 is gray and cannot be edited
3dsmax plug-in development traversal node object and object acquisition and inode transformation matrix description
[problem handled] -nvidia SMI command cannot obtain the GPU process number of its own container and the external GPU process number
Use of laravel carbon time processing class
Complete software development process
laravel 事件 & 监听
What will Web3 bring in the future?
Using recyclerreview to show banner is very simple
Gin configuration file
6月第4周榜单丨飞瓜数据UP主成长排行榜(哔哩哔哩平台)发布!
Handsontable数据网格组件
Understanding and application of Qt5 layout in creation
【多源bfs】934. Shortest Bridge
System. Csrebot for commandline