MDC實現traceId日志追蹤


分布式系統中,最棘手的問題往往是日志跟蹤, 多台機器多個server,調用鏈的關系、連續性顯得格外重要。我們需要一個唯一標識來記錄每條日志的輸出,並希望其傳遞下去。
一個很簡單的方式就是集中在日志中。

package com.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;

/**
 * 統一日志追蹤
 */

@Slf4j
@Component
@Aspect
public class TraceIdHandler {

    private static final String TRACE_ID = "traceId";

    @Before(value = "execution(* com..*.*(..))")
    public void excuteBefore() {
        if (StringUtils.isBlank(MDC.get(TRACE_ID))) {
            String traceId = IdGenerator.get() + "-" + ((int) ((Math.random() * 9 + 1) * 100000));
            MDC.put(TRACE_ID, traceId);
        }
    }
}

 


關鍵是--> [%X{traceId}]
<RollingRandomAccessFile name="running-log"
fileName="${LOG_HOME}/${FILE_NAME}.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout
pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line][%X{traceId} %X{uid} %X{fundAccount}] - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>

需要添加依賴slf4j【slf4j的作用參考:https://www.cnblogs.com/xrq730/p/8619156.html】:

<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.6.2</version>
            <optional>true</optional>
        </dependency>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM