当前位置:网站首页>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
边栏推荐
- 尝试新的可能
- Ks009 implementation of pet management system based on SSH
- [dynamic planning] path dp:931 Minimum Falling Path Sum
- 元宇宙为 VR/AR 带来的新机会
- [deepin] common sets
- [problem handled] -nvidia SMI command cannot obtain the GPU process number of its own container and the external GPU process number
- Exploration and practice of "flow batch integration" in JD
- Working for eight years as a programmer, but with a salary of three years after graduation, it's too late to be enlightened again
- Understanding and application of Qt5 layout in creation
- Necessary tools for testing - postman practical tutorial
猜你喜欢

使用 C# 创造 ASCII 艺术

After working for 6 years, let's take stock of the golden rule of the workplace where workers mix up

Basic knowledge 3 - standard unit library

Exploration and practice of "flow batch integration" in JD

测试必备工具-Postman实战教程

图的连通性基础

数据探索电商平台用户行为流失分析

Uniapp official component clicking item is invalid, solution

With regard to the white box test, you have to master these skills~

1500w播放下还藏着什么热点?B站2个未来趋势你不得错过
随机推荐
Visual studio 2019 Download
数字IC设计流程总结
Some items of OCR
日志 logrus第三方库的使用
Sort custom function
Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base
【agora】用户管理
【Content-Type请求头的内容】
flutter报错 -- The argument type ‘Function‘ can‘t be assigned to the parameter type ‘void Function()?‘
软件测试的可持续发展,必须要学会敲代码?
未来的 Web3会带来什么?
孙宇晨接受瑞士媒体Bilan采访:熊市不会持续太久
Typora的使用
[queue] 933 Number of Recent Calls
Use strictmode strictmode principle (1)
视频教程 | 长安链推出系列视频教程合集(入门)
laravel 事件 & 监听
"Open math input panel" in MathType editing in win11 is gray and cannot be edited
gin 配置文件
Digital IC design process summary