1. 程式人生 > >AOP+MDC實現traceId日誌追蹤

AOP+MDC實現traceId日誌追蹤

/**
 * 統一日誌追蹤處理器
 *
 * @author dengy
 * @since jdk1.8
 */

@Slf4j
@Component
@Aspect
public class TraceIdHandler {

    private static final String TRACE_ID = "traceId";

    @Before(value = "execution(* com.xxx.exbiz.trans..*.*(..))")
    public void aroundHandle() {
        if (StringUtils.isBlank(MDC.get(TRACE_ID))) {
            String traceId = DateUtil.getSysTime() + "-" + ((int) ((Math.random() * 9 + 1) * 100000));
            MDC.put(TRACE_ID, traceId);
        }
    }
}
關鍵是--> [%X{traceId}]

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder class="com.llpay.framework.autoconfigure.logging.logback.SecurePatternLayoutEncoder">
	        <pattern>%d %-5p [%X{traceId}] %t [%c] - %m%n</pattern>
	        <charset>UTF-8</charset>
		</encoder>
	</appender>