当前位置:网站首页>LogBack & MDC & a simple use
LogBack & MDC & a simple use
2022-07-22 10:13: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.
边栏推荐
- 将mariadb里的数据导入到columnstore里
- Causal of maxscale_ Reads parameter
- C WinForm DataGridView column full width
- Spark SQL:MySQL经典50题(SQL版和Spark版)
- 直接修改/etc/crontab 文件内容,定时任务不生效
- Atr5179 single pole double throw switch chip replaces as179-92lf
- ansible简单使用示例
- Ci24r1 low-cost 2.4G wireless transceiver chip replaces xn297 compact si24r1
- 纯函数与高阶函数
- oracle怎样将字符串转为多行
猜你喜欢
mariadb spider分片引擎初体验
warning: [mariadbmon] The current master server ‘srv-cls01-02‘ is no longer valid because it is in r
JVM-jstat(虚拟机统计信息监视工具)的使用
spark Json日志分析
Spark SQL 内置函数和自定义函数UDF
Constructors and destructors of derived classes
How Oracle converts strings into multiple lines
oracle用一条sql查出哪些数据不在某个表里
maxscale的causal_reads参数
Jiayuan "great earthquake" of the century
随机推荐
记一次GCEasy的垃圾收集分析
mariadb spider分片引擎初体验
Friend functions and friend classes
Oracle uses an SQL to find out which data is not in a table
How can ZABBIX customize MySQL monitoring items and trigger alarms
How Oracle escapes single quotation marks
NewSQL数据库数据模型设计
jvm的jps简单使用
中国最幸运极客:二十出头身家过亿,三次创业全身而退
WPF textbox limits two ways to enter numbers only
mysql 主从同步出问题,重新修复从库(转)
JVM jhat (virtual machine heap dump snapshot analysis tool)
MySQL之插入、修改、删除表数据
Ci24r1 low-cost 2.4G wireless transceiver chip replaces xn297 compact si24r1
mysql grant 用户权限总结
Access to derived class members
从数据标准到数据库设计:解决基础数据标准落地的最后一公里难题(下)
Atr5179 single pole double throw switch chip replaces as179-92lf
WPF TextBox限制只能输入数字的两种方法
MariaDB audit plug-in