使用logback实现请求链路跟踪,快速分析日志排错

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1. 在logback.xml中增加如下参数

%X{traceId}

 
	 
		 
		%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} [%X{traceId}] ${PID:- } [%thread] [%-40.40logger{39}:%line] %m%n  
	 

2.该参数可以写在任何你想要输出日志的地方。

编写一个自定义注解

@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LogDescription {

String value() default "";

}

3.使用AOP拦截该注解

@Component
@Aspect
public class LogBackAop {

@Pointcut("@annotation(com.choice.scm.utils.logback.LogDescription)")
public void logPointcut() { }


@Around("logPointcut()")
public Object logPrefixPush(ProceedingJoinPoint point) {
    LogDescription logDescription;
    StringBuilder traceId = new StringBuilder();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    if (method.getDeclaringClass().isAnnotationPresent(LogDescription.class)) {
        logDescription = method.getDeclaringClass().getAnnotation(LogDescription.class);
        traceId.append(logDescription.value()).append("::");
    }
    if (method.isAnnotationPresent(LogDescription.class)) {
        logDescription = method.getAnnotation(LogDescription.class);
        traceId.append(logDescription.value()).append("::");
    }
    MDC.put("traceId", traceId.toString());
    try {
        return point.proceed();
    } catch (Throwable throwable) {
        throw new RuntimeException(throwable);
    } finally {
        MDC.clear();
    }
}
}

4.在需要应用的地方添加注解

使用logback实现请求链路跟踪,快速分析日志排错_第1张图片

转载于:https://my.oschina.net/gentlelions/blog/3052706

你可能感兴趣的:(使用logback实现请求链路跟踪,快速分析日志排错)