springboot使用唯一ID记录日志,迅速定位异常位置
日志的作用不言而喻,尤其在线上用户量大的情况下,日志及时准确的定位至关重要
首先看结果
- 日志输出:
2020-01-02 14:02:46.471 [http-nio-8081-exec-2] INFO cn.wangsr.aop.LogAspect 8c05a294-72b4-4f9f-a160-9646c4d3a289 URLParamName : null
2020-01-02 14:02:46.472 [http-nio-8081-exec-2] INFO cn.wangsr.aop.LogAspect 8c05a294-72b4-4f9f-a160-9646c4d3a289 URLParamValue :
2020-01-02 14:02:46.473 [http-nio-8081-exec-2] INFO cn.wangsr.aop.LogAspect 8c05a294-72b4-4f9f-a160-9646c4d3a289 URL: http://127.0.0.1:8081/sys/getWxApiToken, HTTP_METHOD: GET, IP: 127.0.0.1, Method: cn.wangsr.controller.wechat.SysAdminController.getWxApiToken
2020-01-02 14:02:47.351 [http-nio-8081-exec-2] INFO c.w.advice.GlobalExceptionAdvice 8c05a294-72b4-4f9f-a160-9646c4d3a289 Exception message : / by zero
2020-01-02 14:02:47.351 [http-nio-8081-exec-2] INFO c.w.advice.GlobalExceptionAdvice 8c05a294-72b4-4f9f-a160-9646c4d3a289 Exception from : {}
2020-01-02 14:02:47.353 [http-nio-8081-exec-2] INFO c.w.advice.GlobalExceptionAdvice 8c05a294-72b4-4f9f-a160-9646c4d3a289 Exception print : {}
- 再看错误响应:
{
"requestId": "8c05a294-72b4-4f9f-a160-9646c4d3a289",
"code": "500",
"message": "/ by zero",
"path": "/sys/getWxApiToken",
"data": {}
}
可以看到响应结果中有个id(8c05a294-72b4-4f9f-a160-9646c4d3a289),而这个id是和日志输出中的前面一部分相同的,即每个请求都有唯一的日志id,通过这个我们可以直接在服务器中通过相应的命令查询定位
for example:
ps -1000f xxxlogs.log | grep 8c05a294-72b4-4f9f-a160-9646c4d3a289
- 如何使用
- 首先在过滤器中加入以下(注意引入的是springboot自带的包 org.slf4j.MDC):
private final String REQUEST_ID = "request_id";
...
//请求唯一id
String uid = UUID.randomUUID().toString();
MDC.put(REQUEST_ID,uid);
request.setAttribute(REQUEST_ID,uid);
- 然后在日志文件(logback-spring.xml)中配置({request_id}与filter中变量保持一致):
示例(这个只是在要输出的配置中加上前缀 %X{request_id}):
<pattern>%X{request_id} %d %-5level %logger[%line] %X{request_id} %msg%n</pattern>
- 如果配置没问题那么每次请求完成打印的日志均会携带唯一id
- 错误响应代码:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public final class ExceptionResult {
private String requestId;
private String code;
private String message;
private String path;
private final Map<String,Object> data = new HashMap();
}
...
ExceptionResult handleExceptionForErrorOne(Exception e, HttpServletRequest request){
ExceptionResult exceptionResult = ExceptionResult.builder()
.requestId((String)request.getAttribute("request_id"))
.code(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))
.message(e.getMessage())
.path(request.getRequestURI())
.build();
logger.info("Exception message : {}",e.getMessage());
logger.info("Exception from : {}",e.getCause());
logger.info("Exception print : {}",e);
return exceptionResult;
}
网友评论