- 上一篇
- java springboot 初体验 (五)对接apollo
- https://www.cnblogs.com/zwjvzwj/p/16602858.html
- pom文件中添加依赖
-
<!-- 切面 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
-
- 新增一个切面package和文件
-
package com.zwj.zwjproject.aspect; import com.google.gson.Gson; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * @ClassName: WebLogAspect * @Author zhangwujie * @Date 2022/8/22 11:32 上午 * @Description: */ @Aspect @Slf4j @Component public class WebLogAspect { /** 以 controller 包下定义的所有请求为切入点 */ @Pointcut(value = "execution(public * com.zwj.zwjproject.controller..*.*(..)))") public void webLog(){} /** * @apiNote 切点之前植入 * @param joinPoint joinPoint */ @Before("webLog()") public void doBefore(JoinPoint joinPoint) { try { // 开始打印请求日志 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); assert attributes != null; HttpServletRequest request = attributes.getRequest(); // 打印请求相关参数 log.info("========================================== Start =========================================="); // .concat(" -- request_id】:").concat(requestId); String sb = "".concat("请求 URL : ").concat(request.getRequestURL().toString()) .concat(" -- 请求 Method : ").concat(request.getMethod()) .concat(" -- 请求 query :").concat(request.getQueryString()) .concat(" -- 请求 body :").concat(Arrays.toString(joinPoint.getArgs())) .concat(" -- 请求 IP :").concat( request.getRemoteAddr()) .concat(" -- 请求类名:").concat(joinPoint.getSignature().getDeclaringTypeName()) .concat(" -- 请求方法名 :").concat(joinPoint.getSignature().getName()) .concat(" -- 请求参数 :").concat(request.getParameterMap().toString()); log.info("Request Args : {}", sb); } catch (Exception e) { log.info("Request Args catch error msg : {}", e.getMessage()); } } /** * 在切点之后织入 */ @After("webLog()") public void doAfter() { // 每个请求之间空一行 log.info(""); } /** * 环绕 * @param proceedingJoinPoint proceedingJoinPoint * @return Object * @throws Throwable Throwable */ @Around("webLog()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = proceedingJoinPoint.proceed(); // 打印出参 log.info("Response Args : {}", new Gson().toJson(result)); // 执行耗时 log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); // 结束 log.info("=========================================== end ==========================================="); return result; } }
-
-
调用接口查看效果
- 下一篇
-