SpringBoot AOP统一处理Web请求日志
引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@Around("execution(public * com.daxiong.mall.controller.*.*(..))") public Object webLog(ProceedingJoinPoint pjp) {}
记录请求 URL:
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); log.info("URL : " + request.getRequestURL().toString());
请求类型:
log.info("HTTP_METHOD : " + request.getMethod());
IP 地址:
log.info("IP : " + request.getRemoteAddr());
记录请求的 类以及方法:
log.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
记录请求参数:
log.info("ARGS : " + Arrays.toString(pjp.getArgs()));
执行方法,处理请求
Object res = pjp.proceed(pjp.getArgs());
记录响应结果 使用 jackson 将帝乡转换为 json 格式。
log.info("RESPONSE : " + new ObjectMapper().writeValueAsString(res));
全部:
/** * 打印请求和响应信息 */ @Aspect @Component public class WebLogAspect { private final Logger log = LoggerFactory.getLogger(WebLogAspect.class); @Around("execution(public * com.daxiong.mall.controller.*.*(..))") public Object webLog(ProceedingJoinPoint pjp) throws Throwable { log.info("========================新的请求========================"); // 收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); log.info("URL : " + request.getRequestURL().toString()); log.info("HTTP_METHOD : " + request.getMethod()); // 若是 localhost,则会返回 0:0:0:0:0:0:0:1 log.info("IP : " + request.getRemoteAddr()); log.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName()); log.info("ARGS : " + Arrays.toString(pjp.getArgs())); // 执行方法,处理请求 Object res = pjp.proceed(pjp.getArgs()); // 记录响应 log.info("RESPONSE : " + new ObjectMapper().writeValueAsString(res)); return res; } }
总结
到此这篇关于SpringBoot AOP统一处理Web请求日志的文章就介绍到这了,更多相关SpringBoot AOP统一处理Web请求日志内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
编程 | 2023-02-24 21:36
编程 | 2023-02-21 12:51
编程 | 2023-02-21 12:47
编程 | 2023-02-21 00:15
编程 | 2023-02-21 00:08
编程 | 2023-02-20 21:46
编程 | 2023-02-20 21:42
编程 | 2023-02-20 21:36
编程 | 2023-02-20 21:32
编程 | 2023-02-20 18:12
网友评论