SpringBoot AOP统一处理Web请求日志

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

SpringBoot AOP统一处理Web请求日志

  • 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 新建过滤器 WebLogAspect.java
    • 使用 @Aspect 注解修饰说明当前类 是一个切面类。
    • 使用 @Component注解修饰标记 切面类 为组件这样 IOC 容器 会为其实例化和管理< bean>
  • 定义切面方法webLog() 方法名随意
    • 使用环绕通知 @Around(“execution(public * com.daxiong.mall.Controller..(…))”) 注解修饰指定 切面范围。
@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 地址
    • 若是本地 localhost则会返回 ipv6 0:0:0:0:0:0:0:1
log.info("IP : " + request.getRemoteAddr());
  • 记录请求的 类以及方法
    • 使用 环绕通知的 ProceedingJoinPoint 参数。
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;
    }
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring