問題背景
項目中通過sleuth
實現了統一的traceId
注入,在生產環境進行日志追溯時比較方便。但是在使用xxl-job進行定時任務管理時,卻發現xxl-job線程打印出來的日志沒有traceId
,查詢日志時十分不方便,于是通過使用Spring aop
的方式對使用了@XxlJob
注解的方法注入traceId
代碼:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.sleuth.Span;
import org.springframework.stereotype.Component;import java.util.UUID;@Slf4j
@Aspect
@Component
public class XxlJobAspect {/*** 打印統一日志,注入traceId* @author 只有影子* @param joinPoint*/@Before("@annotation(com.xxl.job.core.handler.annotation.XxlJob)")public void beforeMethod(JoinPoint joinPoint) {// 注入traceId// MDC` put的key可以自己定義,在我的項目里因為用的是`X-B3-TraceId`,所以用的是Span.TRACE_ID_NAME,這里填實際用到的keyMDC.put(Span.TRACE_ID_NAME,UUID.randomUUID().toString());// xxl定時任務統一日志String className = joinPoint.getTarget().getClass().getSimpleName();String methodName = joinPoint.getSignature().getName();String args = JSON.toJSONString(joinPoint.getArgs(), SerializerFeature.IgnoreNonFieldGetter);log.info("執行xxl-job自動任務:{}.{},參數:{}", className, methodName, args);}
}
說明
通過增加以上類,即可實現traceId
注入,同時也增加了統一日志打印,不需要在每個定時任務入口都打印日志(如果不需要也可以去掉)。
相關文章:
【鏈路追蹤】Java多線程之間日志traceId傳遞