注:记录开发,自己总结,随便写写,不喜勿喷。
痛点描述
之前讲过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;
}
}
切点就是常用的那些注解,是不是很简单?赶紧拿去试试。