0%

SpringBoot 拦截 response 记录日志

直接使用AOP的拦截器,调用AfterReturning即可。
废话不多说直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.gs.techpub.filter;

import com.gridsum.techpub.utils.JsonUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class ResponseFilter {

private Logger logger = LoggerFactory.getLogger(this.getClass());
@AfterReturning(returning = "ret", pointcut = "execution( * com.gs.techpub.controller.*.*(..))")
public void doAfterReturning(Object ret) {
logger.info("返回值 : " + JsonUtil.getInstance().toJson(ret));
}
}

记得加上依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>