|
|
@@ -9,8 +9,12 @@ import org.aspectj.lang.annotation.Around;
|
|
|
import org.aspectj.lang.annotation.Aspect;
|
|
|
import org.aspectj.lang.annotation.Pointcut;
|
|
|
import org.aspectj.lang.reflect.MethodSignature;
|
|
|
+import org.slf4j.MDC;
|
|
|
import org.springframework.core.annotation.Order;
|
|
|
import org.springframework.core.io.InputStreamSource;
|
|
|
+import org.springframework.web.context.request.RequestContextHolder;
|
|
|
+import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
+import javax.servlet.http.HttpServletRequest;
|
|
|
|
|
|
import java.time.LocalDateTime;
|
|
|
import java.util.HashMap;
|
|
|
@@ -28,17 +32,32 @@ public class CatchLogAspect {
|
|
|
|
|
|
@Around("pointcut()")
|
|
|
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
|
|
- String traceId = UUID.randomUUID().toString().replace("-", "");
|
|
|
+// String traceId = UUID.randomUUID().toString().replace("-", "");
|
|
|
|
|
|
+ // 1. 获取 HttpServletRequest
|
|
|
+ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
|
|
+
|
|
|
+ // 2. 从请求头获取日志ID(假设header名为X-Trace-Id)
|
|
|
+ String traceId = request.getHeader("X-Trace-Id");
|
|
|
+
|
|
|
+ // 3. 如果网关未传递则生成新ID
|
|
|
+ if (traceId == null || traceId.isEmpty()) {
|
|
|
+ traceId = UUID.randomUUID().toString().replace("-", "");
|
|
|
+ }
|
|
|
+
|
|
|
+ MDC.put("X-Trace-Id", traceId);
|
|
|
Object response = null;
|
|
|
try {
|
|
|
+ logRequest(joinPoint, traceId);
|
|
|
response = joinPoint.proceed();
|
|
|
response = wrapApiResult(response);
|
|
|
+ logResponse(response, traceId);
|
|
|
} finally {
|
|
|
if (response instanceof ApiResult) {
|
|
|
((ApiResult<?>) response).setTraceId(traceId);
|
|
|
((ApiResult<?>) response).setDateTime(LocalDateTime.now());
|
|
|
}
|
|
|
+ MDC.remove("X-Trace-Id");
|
|
|
}
|
|
|
return response;
|
|
|
}
|
|
|
@@ -72,7 +91,7 @@ public class CatchLogAspect {
|
|
|
}
|
|
|
|
|
|
if (!paramMap.isEmpty()) {
|
|
|
- log.debug("[traceId:{}] REQUEST PARAMS: {}", traceId, JSON.toJSONString(paramMap));
|
|
|
+ log.info("[traceId:{}] REQUEST PARAMS: {}", traceId, JSON.toJSONString(paramMap));
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
log.error("[traceId:{}] 请求日志记录失败: {}", traceId, e.getMessage(), e);
|
|
|
@@ -85,7 +104,7 @@ public class CatchLogAspect {
|
|
|
private void logResponse(Object response, String traceId) {
|
|
|
try {
|
|
|
if (response != null) {
|
|
|
- log.debug("[traceId:{}] RESPONSE: {}", traceId, JSON.toJSONString(response));
|
|
|
+ log.info("[traceId:{}] RESPONSE: {}", traceId, JSON.toJSONString(response));
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
log.error("[traceId:{}] 响应日志记录失败: {}", traceId, e.getMessage(), e);
|