Bladeren bron

传递MDC

刘立冬 1 maand geleden
bovenliggende
commit
e6559a898e

+ 2 - 1
risk-control-core/src/main/java/com/tzld/piaoquan/risk/control/aop/RequestLogAspect.java

@@ -63,7 +63,8 @@ public class RequestLogAspect {
             data.put("logTraceId", traceId);
             data.put("requestBody", JSON.toJSONString(joinPoint.getArgs()));
             data.put("responseBody", JSON.toJSONString(result));
-            loghubService.asyncSubmitLog(aliyunLogProject, aliyunLogLogstoreRequest, "", data);
+            Map<String, String> mdcContext = MDC.getCopyOfContextMap();
+            loghubService.asyncSubmitLog(aliyunLogProject, aliyunLogLogstoreRequest, "", data, mdcContext);
             return result;
         } finally {
             // 确保在方法执行完毕后清除 traceId

+ 3 - 1
risk-control-core/src/main/java/com/tzld/piaoquan/risk/control/service/LoghubService.java

@@ -14,4 +14,6 @@ public interface LoghubService {
      * @param data
      */
     void asyncSubmitLog(String project, String logStore, String topic, Map<String, Object> data);
-}
+    void asyncSubmitLog(String project, String logStore, String topic, Map<String, Object> data,Map<String, String> mdcContext );
+
+    }

+ 15 - 0
risk-control-core/src/main/java/com/tzld/piaoquan/risk/control/service/impl/LoghubServiceImpl.java

@@ -4,6 +4,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import com.tzld.commons.aliyun.log.AliyunLogManager;
 import com.tzld.piaoquan.risk.control.service.LoghubService;
 import lombok.extern.slf4j.Slf4j;
+import org.slf4j.MDC;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
@@ -52,4 +53,18 @@ public class LoghubServiceImpl implements LoghubService {
     public void asyncSubmitLog(String project, String logStore, String topic, Map<String, Object> data) {
         pool.execute(() -> aliyunLogManager.sendLog(project, logStore, topic, data));
     }
+
+    @Override
+    public void asyncSubmitLog(String project, String logStore, String topic, Map<String, Object> data,Map<String, String> mdcContext ) {
+        pool.execute(() -> {
+            if (mdcContext != null) {
+                MDC.setContextMap(mdcContext);  // 恢复 MDC
+            }
+            try {
+                aliyunLogManager.sendLog(project, logStore, topic, data);
+            } finally {
+                MDC.clear();
+            }
+        });
+    }
 }