springboot通过spring AOP记录接口请求参数日志

通过spring AOP记录接口请求参数日志,方便并节省代码,只需要在一个类中写记录代码,就可应用的所有请求接口中。
首先,添加包
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.8.13</version>
</dependency>

创建类AopHandler,请求参数是健值对的记录方法

@Aspect
@Component
@Slf4j
public class AopHandler {

    @Around("@annotation(requestMapping)")
    public Object recordCallLog(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {
        long start = System.currentTimeMillis();

        Signature signature = pjp.getSignature();
        String clazz = signature.getDeclaringTypeName();
        String method = signature.getName();
        Object[] parameterValues = pjp.getArgs();

        StringBuilder builder = new StringBuilder();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNamess = methodSignature.getParameterNames();
        for (int i = 0; i < parameterNamess.length; i++) {
            if (i == 0) {
                builder.append("?");
            }
            builder.append(parameterNamess[i] + "=" + parameterValues[i].toString());
            if (i < parameterNamess.length - 1) {
                builder.append("&");
            }
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String path = request.getRequestURL().toString();

        log.info(">>>>>>:" + path + builder.toString());

        Object result = pjp.proceed();

        long usedTime = System.currentTimeMillis() - start;

        log.info("<<<<<<:" + method + "|耗时:" + usedTime + "毫秒");

        return result;
    }
}

若请求参数是对象的,如

@RequestMapping("/test")
public String test(@RequestBody MqMsg msg){
    return "ok";
}

则aop的参数日志记录方法为:

@Aspect
@Component
@Slf4j
public class AopHandler {

    @Around("@annotation(requestMapping)")
    public Object recordCallLog(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {
        long start = System.currentTimeMillis();

        String params = "";//多个参数时出错 JsonUtil.toJson(pjp.getArgs());

        Object[] args = pjp.getArgs();
        Object[] arguments  = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                //ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
                //ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
                continue;
            }
            arguments[i] = args[i];
        }
        if (arguments != null) {
            try {
                params = JsonUtil.toJson(arguments);
            } catch (Exception e) {
                params = arguments.toString();
            }
        }

        Signature signature = pjp.getSignature();
        String method = signature.getName();

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String path = request.getRequestURL().toString();

        log.info(">>>>>>:" + path + params);

        Object result = pjp.proceed();

        String json = "";
        if(null!=result){
            json = JsonUtil.toJson(result);
        }
        long usedTime = System.currentTimeMillis() - start;

        //log.info("<<<<<<:" + method + "|耗时:" + usedTime + "毫秒");
        log.info("<<<<<< 结束请求:" + path + "|耗时:" + usedTime + "毫秒|响应:" + json );

        return result;
    }
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot AOPSpring框架的一个核心功能之一,它可以用于全局请求日志处理等方面。在Spring Boot中使用AOP,首先需要创建一个Spring Boot Web项目,并引入相关的依赖。这些依赖包括org.springframework.boot:spring-boot-starter、org.springframework.boot:spring-boot-starter-aop和org.springframework.boot:spring-boot-starter-web。 AOP的源码在Spring Boot中位于spring-boot-autoconfigure-2.3.7.RELEASE.jar这个jar包中,该jar包是Spring Boot的自动配置jar包之一。通过引入这些依赖,我们可以使用Spring Boot AOP来实现一些切面编程的功能,比如全局请求日志处理等。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [SpringBootAOP的使用](https://blog.csdn.net/weixin_45583303/article/details/118565966)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [SpringBootSpring核心AOP详解](https://blog.csdn.net/qq_42263280/article/details/127696254)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值