当前位置:网站首页>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.
边栏推荐
- [TA frost wolf umay - "hundred people plan] Figure 3.3 surface subdivision and geometric shader large-scale grass rendering
- The difference between YPbPr and YCbCr
- ctfshow ThinkPHP专题 1
- [markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)
- Semaphore详解
- 【C】 Recursive and non recursive writing of binary tree traversal
- HCIP MGRE实验 第三天
- Research on parameter setting of MATLAB FFT
- Detailed explanation of stat function
- [deserialization vulnerability-01] Introduction to serialization and deserialization
猜你喜欢

MicroBlaze adds a custom IP core and attaches the Axi bus to realize ssd1306 OELD drive

Video playback | how to become an excellent reviewer of international journals in the field of Geoscience and ecology?

HDU5667 Sequence

High speed ADC test experience

《Nature》论文插图复刻第3期—面积图(Part2-100)

Jmeter-Runtime控制器

Paging query of employee information of black maredge takeout

CSDN会员的魅力何在?我要他有什么用?

Research on parameter setting of MATLAB FFT
![About [software testing - interview skills and precautions for automated testing] - talk freely](/img/c2/bd1a52bdd7ab07878348b6216012f0.png)
About [software testing - interview skills and precautions for automated testing] - talk freely
随机推荐
MOS管 —— 快速复苏应用笔记(壹)[原理篇]
Fiddler packet capture tool summary
The third day of hcip mGRE experiment
Easy to understand ES6 (IV): template string
stream流
MicroBlaze adds a custom IP core and attaches the Axi bus to realize ssd1306 OELD drive
IT圈中的Bug的类型与历史
Talk about software testing - automated testing framework
字符串——剑指 Offer 05. 替换空格
Code of login page
Directional crawling Taobao product name and price (teacher Songtian)
Text message verification of web crawler
Nodejs CTF Foundation
Self taught software testing talent -- not covered
Robot framework official tutorial (I) getting started
In BS4.String and Difference between text
What is the charm of CSDN members? What's the use of him?
Performance test summary (I) -- basic theory
网络爬虫之短信验证
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)