Logback的MDC技术(来源自官网翻译)
MDC全称Mapped Diagnostic Context,翻译为上下文信息诊断映射。为了追踪不同客户端对服务端的请求,并记录他们的日志调用信息。一个简单的做法就是为每个提供服务的客户端请求单独的记录日志信息。LOGBACK利用了一系列这个技术应用到SLF4J API,形成了MDC。
为了单独的记录每一条请求,用户需要将上下文信息记录到MDC中。MDC的类中仅仅包含了几个静态方法,它使得开发者可以将信息放到上下文中,然后随后可以被logback的相关组件检索到。MDC基于每个线程去管理上下文信息。典型地,当开始服务一个新的客户端请求时,开发者将插入相关的上下文信息,比如clientID,clientIP和相关参数等。logback如果做了相关的配置,那么将在日志体里面自动包含所有这些信息。
请注意,根据logback-classic实现的MDC,值会以中等的频率放置到MDC中。另外一个子线程不回继承父线程的参数值。
-
高级用法
MDC技术被广泛的用在客户端和服务端的架构中。典型的就是多个客户端请求将由多个服务端线程去提供服务,尽管MDC提供的方法都是静态的,但是每个上下文信息是基于线程控制的,这就允许每个服务线程有明显的MDC标记。MDC的诸如get和put操作影响的仅仅是当前线程和它的子线程。因此没有必要担心MDC在编程过程中的线程安全问题(猜测应该和ThreadLocal有关)。
下面的例子是更加高级的用法,它展示了MDC怎样被应用在客户端服务端模配置中。服务端实现了NumberCruncher接口,这个接口有唯一的方法factor()。使用RMI技术,客户端触发服务端的这个方法检索不同的整型因子。
interface接口:
package chapters.mdc;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* NumberCruncher factors positive integers.
*/
public interface NumberCruncher extends Remote {
/**
* Factor a positive integer number and return its
* distinct factor's as an integer array.
* */
int[] factor(int number) throws RemoteException;
}
服务端代码:
View Javadoc
1 /**
2 * Logback: the reliable, generic, fast and flexible logging framework.
3 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4 *
5 * This program and the accompanying materials are dual-licensed under
6 * either the terms of the Eclipse Public License v1.0 as published by
7 * the Eclipse Foundation
8 *
9 * or (per the licensee's choosing)
10 *
11 * under the terms of the GNU Lesser General Public License version 2.1
12 * as published by the Free Software Foundation.
13 */
14 package chapters.mdc;
15
16 import java.rmi.RemoteException;
17 import java.rmi.registry.LocateRegistry;
18 import java.rmi.registry.Registry;
19 import java.rmi.server.UnicastRemoteObject;
20 import java.util.Vector;
21
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.slf4j.MDC;
25
26 import ch.qos.logback.classic.LoggerContext;
27 import ch.qos.logback.classic.joran.JoranConfigurator;
28 import ch.qos.logback.core.joran.spi.JoranException;
29
30 /**
31 * A simple NumberCruncher implementation that logs its progress when
32 * factoring numbers. The purpose of the whole exercise is to show the
33 * use of mapped diagnostic contexts in order to distinguish the log
34 * outpu