web服务器http接口如何统一打出入日志?

文章介绍了如何利用SpringMVC的AOP来解决HTTP接口的日志记录问题。通过定义切点匹配@RequestMapping、@PostMapping和@GetMapping等注解的方法,实现请求开始和结束时的日志打印,包括请求路径、参数、结果和执行时间。对于异步响应,使用CompletableFuture的whenComplete进行日志处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注:记录开发,自己总结,随便写写,不喜勿喷。

痛点描述

之前讲过dubbo服务如何统一打出入日志,http接口同样有这个问题,怎么解决呢?

解决方案

现在web框架基本上都会用SpringMVC(自己造的轮子也差不多),可以考虑用springMVC的拦截器,也可以直接aop,下面给个aop的代码示例。

@Aspect
@Component
public class LogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(esa.restlight.spring.shaded.org.springframework.web.bind.annotation.RequestMapping)" +
            " || @annotation(esa.restlight.spring.shaded.org.springframework.web.bind.annotation.PostMapping)" +
            " || @annotation(esa.restlight.spring.shaded.org.springframework.web.bind.annotation.GetMapping)"
    )
    public void controllerMethods() {
        // Do nothing
    }

    @Around("controllerMethods()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        AsyncRequest request = RequestResponseHolder.getRequest();
        long start = System.currentTimeMillis();
        LOGGER.info("<<==request:{},param {} ==>>", request.path(), pjp.getArgs());
        Object result = pjp.proceed();
//这里对结果区分了异步和同步
        if (result instanceof CompletableFuture) {
            CompletableFuture rspCf = (CompletableFuture) result;
            rspCf.whenComplete((r, e) -> {
                
                LOGGER.info("<<==response:{},param {},result ,{} ,time,{} ==>>",
                        request.path(), pjp.getArgs(), result, System.currentTimeMillis() - start);
                MDC.remove("traceId");
            });
        } else {
            LOGGER.info("<<==response:{},param {},result ,{} ,time,{} ==>>",
                    request.path(), pjp.getArgs(), result, System.currentTimeMillis() - start);
        }
        return result;
    }
}

切点就是常用的那些注解,是不是很简单?赶紧拿去试试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值