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

博客介绍了在Java和Python相关开发中日志输出的操作。首先要在logback.xml中增加%X{traceId}参数,该参数可写在任意想输出日志处。接着需编写自定义注解,用AOP拦截此注解,最后在需要应用的地方添加注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.在需要应用的地方添加注解

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值