栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

基于springboot,通过拦截器实现请求和响应报文日志输出打印

Java 更新时间:发布时间: 百科书网 趣学号

1、请求controller入口

@Controller
public class IndexController {
@GetMapping({"/", "/index"})
    public String index() {
        return "index";
    }
}

2、拦截器

@Aspect
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Pointcut(value = "execution(public * com.example.controller..*.*(..))")
    public void reqOpenAPILog() {
    }
        
    @Before("reqOpenAPILog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
 	        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求 url
        logger.info("Request URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        logger.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        logger.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        logger.info("Request IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        logger.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));

    
    @After("reqOpenAPILog()")
    public void doAfter() throws Throwable {
        // TODO: 2022/6/6 doSth(). 
    }
    
    @Around("reqOpenAPILog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        logger.info("========================================== Start ==========================================");
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        logger.info("Response Args  : {}", new Gson().toJson(result));
        // 执行耗时
        logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        logger.info("=========================================== End ===========================================");
        return result;
    }


 }

3、浏览器请求:http://localhost:9091/index

4、日志控制台输出

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/957083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号