Skip to content

Commit 3777be2

Browse files
committed
Spring Boot 中使用 logback  配置
1 parent 02be3a9 commit 3777be2

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

‎spring-boot-logback/src/main/java/io/ymq/logback/config/commons/ControllerInterceptor.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,16 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
4040
@Override
4141
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
4242
/* 线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
43-
MDC.remove("requestUUID");
4443
LOGGER.info("ControllerInterceptor postHandle 请求处理之后清除 logback MDC requestUUID");
44+
MDC.remove("requestUUID");
4545
}
4646

4747
//整个请求处理完毕回调方法
4848
@Override
4949
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
5050
/*整个请求线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
51-
MDC.clear();
5251
LOGGER.info("ControllerInterceptor afterCompletion 整个请求处理完毕清除 logback MDC requestUUID");
52+
MDC.clear();
53+
5354
}
5455
}

‎spring-boot-logback/src/main/java/io/ymq/logback/config/commons/LogAspect.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
import org.aspectj.lang.reflect.MethodSignature;
1111
import org.slf4j.Logger;
1212
import org.slf4j.LoggerFactory;
13+
import org.slf4j.MDC;
1314
import org.springframework.stereotype.Component;
1415

1516
import java.lang.reflect.Method;
17+
import java.util.UUID;
1618

1719

1820
/**
@@ -27,13 +29,22 @@ public class LogAspect {
2729
private static final String STRING_START = "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n";
2830
private static final String STRING_END = "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n";
2931

30-
@Pointcut("execution(* io.ymq.logback.controller..*(..))")
32+
@Pointcut("execution(* io.ymq.logback..*(..))")
3133
public void serviceLog() {
3234
}
3335

3436
@Around("serviceLog()")
3537
public Object around(ProceedingJoinPoint joinPoint) {
3638
try {
39+
40+
String requestUUID = MDC.get("requestUUID");
41+
if (requestUUID == null || "".equals(requestUUID)) {
42+
String uuid = UUID.randomUUID().toString();
43+
uuid = uuid.replaceAll("-", "").toUpperCase();
44+
MDC.put("requestUUID", uuid);
45+
log.info("around 在请求处理之前生成 logback requestUUID:{}", uuid);
46+
}
47+
3748
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
3849
Method method = signature.getMethod();
3950
Class<?> targetClass = method.getDeclaringClass();

0 commit comments

Comments
 (0)