当前位置:网站首页>LogBack & MDC & a simple use
LogBack & MDC & a simple use
2022-07-24 11:31:00 【suanday_ sunny】
One of the design goals of logback is to audit and debug complex distributed applications. Most real-world distributed systems need to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. A possible but slightly discouraged approach to differentiate the logging output of one client from another consists of instantiating a new and separate logger for each client. This technique promotes the proliferation of loggers and may increase their management overhead.
In order to run the examples in this chapter, you need to make sure that certain jar files are present on the classpath. Please refer to the setup page for further details.
A lighter technique consists of uniquely stamping each log request servicing a given client. Neil Harrison described this method in the book Patterns for Logging Diagnostic Messages in Pattern Languages of Program Design 3, edited by R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, 1997). Logback leverages a variant of this technique included in the SLF4J API: Mapped Diagnostic Contexts (MDC).
To uniquely stamp each request, the user puts contextual information into the MDC, the abbreviation of Mapped Diagnostic Context.
package org.slf4j;
public class MDC {
//Put a context value as identified by key
//into the current thread's context map.
public static void put(String key, String val);
//Get the context identified by the key parameter.
public static String get(String key);
//Remove the context identified by the key parameter.
public static void remove(String key);
//Clear all entries in the MDC.
public static void clear();
}
The next application named SimpleMDC demonstrates this basic principle.
Example 7.1: Basic MDC usage ( logback-examples/src/main/java/chapters/mdc/SimpleMDC.java)
package chapters.mdc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.core.ConsoleAppender;
public class SimpleMDC {
static public void main(String[] args) throws Exception {
// You can put values in the MDC at any time. Before anything else
// we put the first name
MDC.put("first", "Dorothy");
[ SNIP ]
Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
// We now put the last name
MDC.put("last", "Parker");
// The most beautiful two words in the English language according
// to Dorothy Parker:
logger.info("Check enclosed.");
logger.debug("The most beautiful two words in English.");
MDC.put("first", "Richard");
MDC.put("last", "Nixon");
logger.info("I am not a crook.");
logger.info("Attributed to the former US president. 17 Nov 1973.");
}
[ SNIP ]
}
The main method starts by associating the value Dorothy with the key first in the MDC. You can place as many value/key associations in the MDC as you wish. Multiple insertions with the same key will overwrite older values. The code then proceeds to configure logback.
For the sake of conciseness, we have omitted the code that configures logback with the configuration file simpleMDC.xml. Here is the relevant section from that file.
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout>
<Pattern>%X{first} %X{last} - %m%n</Pattern>
</layout>
</appender>
Note the usage of the %X specifier within the PatternLayout conversion pattern. The %X conversion specifier is employed twice, once for the key named first and once for the key named last. After obtaining a logger corresponding to SimpleMDC.class, the code associates the value Parker with the key named last. It then invokes the logger twice with different messages. The code finishes by setting the MDC to different values and issuing several logging requests. Running SimpleMDC yields:
Dorothy Parker - Check enclosed.
Dorothy Parker - The most beautiful two words in English.
Richard Nixon - I am not a crook.
Richard Nixon - Attributed to the former US president. 17 Nov 1973.
The SimpleMDC application illustrates how logback layouts, if configured appropriately, can automatically output MDC information. Moreover, the information placed into the MDC can be used by multiple logger invocations.
边栏推荐
- HCIP MGRE实验 第三天
- JMeter interface test steps - Installation Tutorial - script recording - concurrent test
- Zynq TTC usage
- How to convert word to markdown text
- What is cloud native? Why is cloud native technology so popular?
- cgo+gSoap+onvif学习总结:9、go和c进行socket通信进行onvif协议处理
- Semaphore详解
- 哈希——202. 快乐数
- 链表——剑指offer面试题 02.07. 链表相交
- Linked list - Sword finger offer interview question 02.07. linked list intersection
猜你喜欢

Over the weekend, I had a dinner with the technology gurus and talked about the "golden nine and silver ten" peak of the software testing industry [the trend of involution has been formed]

Pytorch learning -- using gradient descent method to realize univariate linear regression

How to choose sentinel vs. hystrix current limiting?

HDU5667 Sequence

Text message verification of web crawler

JMeter if controller

08【AIO编程】

High speed ADC test experience

【C】 Recursive and non recursive writing of binary tree traversal

Introduction to Devops and common Devops tools
随机推荐
Exceptions about configuring Postgres parameters
哈希——15. 三数之和
Semaphore details
[golang] deletion and emptying of map elements in golang
[QNX hypervisor 2.2 user manual]9.2 CmdLine
The difference between YPbPr and YCbCr
[TA frost wolf umay - "hundred people plan] Figure 3.3 surface subdivision and geometric shader large-scale grass rendering
Leetcode 257. 二叉树的所有路径
JPS has no namenode and datanode reasons
Video playback | how to become an excellent reviewer of international journals in the field of Geoscience and ecology?
使用Prometheus+Grafana实时监控服务器性能
Shell script "< < EOF" my purpose and problems
【10】团队协作和跨团队协作
哈希——242.有效的字母异位词
Blue Bridge Cup - binary conversion exercise
How to convert word to markdown text
Two important laws about parallelism
黑马瑞吉外卖之员工信息分页查询
【Golang】golang中time类型的before方法
tcp 服务端接收数据处理思路梳理,以及select: Invalid argument报错 笔记