接口日志是个比较重要日志数据,它是用来记录接口请求处理的详细信息,可包括HTTP响应状态代码、响应时间、URL、协议、请求体大下,HTTP请求方式、客户端IP地址、以及跟踪traceId等。对性能分析和日志排查起着至关重要的作用。目前我们采用的是AOP面向切面编程的方式来实现,废话不说,直接上代码
一、logback日志格式配置
[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%X{traceId}] [%X{companyCode}] %-5level %logger{50} - %msg%n
TraceId:日志跟踪链ID,客户端每次请求接口时都会生成一个TraceId,并在响应head头返回给客户端,同时每条日志记录都必须打印这个traceId,以便系统排错。
二、采用技术
采用AOP面向切面编程方式解决
三、代码
@Aspect
@Component
@Order(1)
public class AccessLogAspect {
private static final Logger LOGGER = LoggerFactory.getLogger("AccessLogger");
//表达式需要注意:..*的意思就是com.fn.(任何目录).controller...
@Pointcut("execution(public * com.fn..*.controller..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
}
@AfterReturning(value = "webLog()", returning = "ret")
public void doAfterReturning(Object ret) throws Throwable {
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
//获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String traceId = request.getHeader("traceId");
if (StringUtils.isEmpty(traceId)) {
traceId = UUID.randomUUID().toString();
}
attributes.getResponse().addHeader("traceId", traceId);
MDC.put("traceId", traceId);
Object result = null;
try {
result = joinPoint.proceed();
} catch (Exception ex) {
throw ex;
} finally {
long endTime = System.currentTimeMillis();
MDC.put("totalTime", String.valueOf(endTime - startTime));
if (result == null) {
LOGGER.error("access url :{}", request.getRequestURI());
} else {
LOGGER.info("access url :{}", request.getRequestURI());
}
}
return result;
}
}