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

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

痛点描述

之前讲过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;
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值