当前位置:网站首页>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
边栏推荐
- 股票开户有哪些优惠活动?另外,手机开户安全么?
- Exploration and practice of "flow batch integration" in JD
- [Qt5 tab] tab label and content hierarchical analysis
- Visual studio 2019 shortcut notes
- [deepin] common sets
- Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base
- 二季度最后一天
- 亲测有效,快速创建JMeter桌面快捷方式
- 【Qt5-基础篇_1】从0开始,德天老师和你一起学习——窗口简介
- Some items of OCR
猜你喜欢

The personal test is effective, and the JMeter desktop shortcut is quickly created

Log logrus third party library usage

neo4j安装、运行以及项目的构建和功能实现

For the sustainable development of software testing, we must learn to knock code?

图的连通性基础

3500 word summary: a complete set of skills that a qualified software testing engineer needs to master

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

软件测试的可持续发展,必须要学会敲代码?

New opportunities for vr/ar brought by metauniverse

Uniapp official component clicking item is invalid, solution
随机推荐
Use of typora
Laravel+redis generates an order number - automatically increase from 1 on the same day
【office办公-pdf篇】pdf合并与拆分让我们摆脱付费软件的功能限制好不好
System. Csrebot for commandline
Some essential differences
Ks009 implementation of pet management system based on SSH
那些一门心思研究自动化测试的人,后来怎样了?
KS009基于SSH实现宠物管理系统
短视频平台开发,依靠DrawerLayout实现侧滑菜单效果
Sort custom function
Mysql database foundation: process control
微生物安全与健康,什么是生物处理?
Open3d point cloud color rendering
Visual studio 2019 Download
gin 配置文件
【队列】933. Number of Recent Calls
Last day of the second quarter
laravel+redis 生成订单号-当天从1开始自增
微生物检测,土壤微生物的作用有哪些?
Gin configuration file