说明
在前后端分离模式下,前端触发后端异常信息时,后端人员需要拿到本次的请求地址,参数等,再次发送请求重现问题,比较麻烦。
方案
如果我们为每个请求生成唯一请求ID,后端日志输出时带上请求id,同时将请求id返回(成功、失败)给前端,以后只需要拿到前端的请求id,在后端日志内搜索id即可快速定位异常信息
内容
public interface LogConstant {
/**
* 日志id {@value}
*/
String REQUEST_ID = "X-Request-Id";
}
public class LogInterceptor implements HandlerInterceptor {
/**
* {@inheritDoc}
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// String xForwardedForHeader = httpServletRequest.getHeader("X-Forwarded-For");
// String remoteIp = httpServletRequest.getRemoteAddr();
String uuid = UUID.randomUUID().toString();
MDC.put(LogConstant.REQUEST_ID, uuid);
httpServletResponse.setHeader(LogConstant.REQUEST_ID, MDC.get(LogConstant.REQUEST_ID));
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
// String uuid = MDC.get(REQUEST_ID);
MDC.remove(LogConstant.REQUEST_ID);
}
/**
* {@inheritDoc}
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
logback-spring.xml
<!-- 文件日志格式 -->
<property name="FILE_LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%X{X-Request-Id}] %-5level %logger{50} - %msg%n"/>
<!-- INFO_FILE配置 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<file>${log_home}/info.log</file>
<!--根据时间来制定滚动策略,即负责滚动也负责触发滚动。-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- fileNamePattern 归档模式 %d 表示按时间归档 yyyy-MM-dd_HH-mm 表示按分钟进行归档 i%表示按日志大小进行归档 -->
<fileNamePattern>${log_home}/zips/info/info_%d{yyyy-MM-dd}.%i.log.zip
</fileNamePattern>
<!-- 保留文件的最大数量 1 表示 只存1分钟前的归档记录 当 归档是根据月份进行归档 maxHistory=1
表示只保存最近一个月的归档记录 -->
<maxHistory>${maxHistory}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- 设置文件大于多少后进行压缩归档 -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
效果请求id
系统会记录本次请求的X-Request-Id,分另记录在Response Header,日志文件,日志系统
Response Header
日志文件
[图片上传失败...(image-dfd6fc-1644831854552)]
日志系统
[图片上传失败...(image-b8738e-1644831854553)]