[笔记系列文章说明]: 该类型的文章是笔者学习过程中整理的学习笔记.
logback的配置详解
1 |
|
MDC,NDC
什么是MDC?
Mapped Diagnostic Context
线程独立自定义Map存储上下文信息,子线程拷贝父线程Map信息
1 | 1.保存信息到上下文 |
什么是NDC?
Nested Diagnostic Context
线程独立自定义栈存储上下文信息,子线程拷贝父线程栈信息
1 | 1.开始调用 |
logback中的MDC
单机MDC使用
1 |
|
跨服务MDC使用(web + dubbo)
使用Spring拦截器HandlerInterceptorAdapter初始化MDC trace
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/**
* 日志跟踪
*/
public class TraceLogInterceptor extends HandlerInterceptorAdapter {
/* 追踪ID */
private static final String TRACE_KEY = "traceId";
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
String a = UUID.randomUUID().toString().replace("-", "");
MDC.put(TRACE_KEY, a);
HttpLogLocalCache.setMsg( a);
return true;
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.clear();
}
}使用Dubbo Filter拦截, RpcContext传递
调用者设置值1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class TraceConsumerFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(TraceConsumerFilter.class);
/* 追踪ID */
private static final String TRACE_KEY = "traceId";
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
LoggerFactory.getLogger(invoker.getInterface().getName()).info(" [dubbo consumer] 服务调用-请求|method:{}|参数:{}| client[ip:{}-protocol:{}]", invocation.getMethodName(), invocation.getArguments(), RpcContext.getContext().getRemoteAddressString(), invoker.getUrl().getProtocol());
try {
logger.debug("MDC-traceId:" + MDC.get(TRACE_KEY));
RpcContext.getContext().setAttachments(MDC.getCopyOfContextMap());
} catch (Exception ex) {
logger.error("dubbo consumer MDC-traceId:reset fail");
}
Result result = invoker.invoke(invocation);
LoggerFactory.getLogger(invoker.getInterface().getName()).info(" [dubbo consumer] 服务调用-返回|method:{}|结果:{}| client[ip:{}-protocol:{}]", invocation.getMethodName(), result, RpcContext.getContext().getRemoteAddressString(), invoker.getUrl().getProtocol());
return result;
}
}
消费者获取值
1 | public class TraceProviderFilter implements Filter { |
调用者配置 spring-dubbo-reference.xml
1 | <dubbo:consumer filter="traceConsumerFilter" version="1.0" timeout="3000" check="${dubbo.reference.check}"/> |
提供者者配置 spring-dubbo-provider.xml
1 | <dubbo:provider protocol="dubbo" filter="traceProviderFilter" version="1.0" timeout="3500" delay="-1" /> |
增加dubbo filter配置
1 | 路径: src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Filter |