接口日志是个比较重要日志数据,它是用来记录接口请求处理的详细信息,可包括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;
}
}
使用AOP实现接口日志记录与追踪,
文章介绍了接口日志的重要性和其包含的关键信息,如HTTP响应状态、响应时间、URL等。通过使用AOP和logback日志框架,文章展示了如何在Java应用中记录并追踪每个接口请求的traceId,以辅助性能分析和问题排查。在代码示例中,详细说明了如何在请求处理的各个阶段插入日志记录。
2191

被折叠的 条评论
为什么被折叠?



