利用AOP实现打印接口调用基本信息(统计接口调用时长)

本文介绍了如何使用Spring AOP来打印接口调用的基本信息,包括请求方式、URL、参数、返回值和执行时间,以便于问题排查。通过在添加了特定注解的接口上调用日志,简化了问题复现过程。


前言

之前写过一篇博客,利用AOP进行接口调用频控设置;这次写一篇利用AOP打印接口调用基本信息。


一、AOP是什么

aop的基本使用和解释,可以参考其他博客,或者Spring的官网:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-api

二、打印接口调用信息

1.why?

有时候线上或者某个环境发生问题,开发同学排查问题,因为无法获知用户的入参而无法复现问题,会比较头疼。所以决定利用AOP的功能,进行接口调用的基本信息打印。

2. code

目前我们只针对了添加GetMapping、PostMapping、PutMapping、DeleteMapping注解的接口调用进行日志打印,主要包括:接口、请求方式、入参、返回值、方法名、接口调用耗时。
当然也可以通过自定义注解来做这件事,或者只关注RequestMapping注解的方法。

@Component
@Aspect
public class RequestLogAspect {
   
   

    @Resource
    private HttpServletRequest request;

    @Around("@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping)" )
    private Object doLog(ProceedingJoinPoint joinPoint) throws Throwable {
   
   
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        Signature signature = joinPoint.getSignature();
        StopWatch stopWatch = new StopWatch();
        System.out.println("接口:" +requestURI + ";请求方式:" + method + ";入参:" + requestParams() + "; 方法名:"+signature.getName());
        stopWatch.start();
        try {
   
   
            Object result = joinPoint.proceed()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值