1. 在logback.xml中增加如下参数
%X{traceId}
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 格式化输出:%d表示日期,LOG_LEVEL_PATTERN:-%5p表示日志级别,${PID:-}父进程,%thread表示线程名,[%-40.40logger{39}:%line]位置信息,类名+行数, %msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} [%X{traceId}] ${PID:- } [%thread] [%-40.40logger{39}:%line] %m%n </pattern>
</encoder>
</appender>
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.在需要应用的地方添加注解