亲宝软件园·资讯

展开

SpringBoot AOP统一处理Web请求日志的示例代码

TryMyBestTo 人气:0

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;
    }
}

总结

加载全部内容

相关教程
猜你喜欢
用户评论