spring切面拦截打印url及body日志

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20201115</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.1</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.9</version>
        </dependency>
        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.4</version>
        </dependency>

代码:

package com.example.testutils.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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;
import java.util.stream.Collectors;


/**
 * @program: analysis-parent
 * @description: 请求日志输出
 * @author: 
 * @create: 2021-05-26 18:13
 */
@Slf4j
@Aspect
@Component
public class ControllerLogAspect {

    @Pointcut("execution(public * com.example.testutils..controllers..*(..))")
    private void controllerLog(){}

    @Before("controllerLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        log.info("=============== Start ===============");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印请求入参
        String requset = Arrays.toString(joinPoint.getArgs());
        if (requset.length() > 1000) {
            requset = requset.substring(0, 1000) + "...";
        }
        String requestData = request.getReader().lines().collect(Collectors.joining()).replaceAll(" ","");
        log.info("Request Args   : {}", JSON.toJSONString(requset));
        log.info("Request Args   : {}", requestData);
    }

    @After("controllerLog()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
        log.info("=============== End ===============");
        // 每个请求之间空一行
        log.info("");
    }

    @Around("controllerLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable t) {
            long end = System.currentTimeMillis();
            long takeTime = end - startTime;
            log.info(request.getRequestURL().toString() + " 执行失败 执行耗时:{} ms,errorMsg:{}", takeTime, t.getMessage());
            throw t;
        }

        // 打印出参
        String response = JSON.toJSONString(result);
        if (response.length() > 1000) {
            response = response.substring(0, 1000) + "...";
        }
        long end = System.currentTimeMillis();
        long takeTime = end - startTime;
        log.info(request.getRequestURL().toString() + " 执行成功 执行耗时:{} ms,ResponseUtil: {}", takeTime, response);
        return result;
    }
}

如果controller里用了@RequestBody的注解,用上述代码会出现getInputStream() has already been called for this request的报错,核心是在于request.getReader().lines().collect(Collectors.joining()).replaceAll(" “,”")这句,原因是ServletRequest的getReader()和getInputStream()两个方法只能被调用一次,此时只要修改此句为String requset = Arrays.toString(joinPoint.getArgs());可以解决该问题

@Before("controllerLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        log.info("=============== Start ===============");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印请求入参
        String requset = Arrays.toString(joinPoint.getArgs());
        if (requset.length() > 1000) {
            requset = requset.substring(0, 1000) + "...";
        }
//        String requestData = request.getReader().lines().collect(Collectors.joining()).replaceAll(" ","");
//        log.info("Request Args   : {}", JSON.toJSONString(requset));
        log.info("Request Args   : {}", requset);
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值