MDC(Mapped Diagnostic Contexts)映射诊断上下文,主要用在做日志链路跟踪时,动态配置用户自定义的一些信息,比如requreqiestId、sessionId等等。MDC使用的容器支持多线程操作,满足线程安全。
使用示例:
此处示例为请求日志拦截中的设置requreqiestId
public Object aroundReq(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String requestId = methodSignature.getMethod().getName() + "-" + System.currentTimeMillis();
***MDC.put("requestId", requestId);***
Object[] args = joinPoint.getArgs();
try {
List<Object> argList = new ArrayList<>();
if (args != null) {
for (Object arg : args) {
if (arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof HttpSession || arg instanceof BindingResult) {
continue;
}
argList.add(arg);
}
}
long startTime = System.currentTimeMillis();
try {
LOGGER.info("方法[{}] 请求参数[{}]", methodSignature.getMethod().getName(), JSONObject.toJSONString(argList));
} catch (Exception e) {
LOGGER.error("方法[{}] 存在请求参数不能序列化,修改上方排除逻辑", methodSignature.getMethod().getName(), e);
}
Object result = joinPoint.proceed(args);
LOGGER.info("方法[{}] 耗时[{}] 返回结果[{}] ", methodSignature.getMethod().getName(), System.currentTimeMillis() - startTime, JSONObject.toJSONString(result));
return result;
} finally {
MDC.clear();
}
}