Logback日志添加唯一追踪ID
【摘要】 问题描述
日志是排查问题的重要依据,但是有时不容易定位报错信息,不明确哪条错误信息对应哪次请求。如果给日志加上唯一的追踪ID,排查就方便多了。 每个请求打印的日志都会有不同的ID,哪个请求出错,根据ID来定位日志。这个ID还会返回给前端,前端发现报错直接把ID给后台人员进行定位分析。
开发环境
SpringBoot - 2.1.10.RELEASEJDK 1.8 ...
问题描述
日志是排查问题的重要依据,但是有时不容易定位报错信息,不明确哪条错误信息对应哪次请求。如果给日志加上唯一的追踪ID,排查就方便多了。
每个请求打印的日志都会有不同的ID,哪个请求出错,根据ID来定位日志。这个ID还会返回给前端,前端发现报错直接把ID给后台人员进行定位分析。
开发环境
- SpringBoot - 2.1.10.RELEASE
- JDK 1.8
创建过滤器
package com.nobody.filter;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.MDC;
/**
* 过滤器,每次请求设置日志唯一追踪ID
*
* @author Μr.ηobοdy
*
* @date 2020-04-29
*
*/
public class LogMDCFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String requestIdKey = "requestId"; String requestId = UUID.randomUUID().toString().replace("-", ""); MDC.put(requestIdKey, requestId); try { filterChain.doFilter(servletRequest, servletResponse); } finally { MDC.remove(requestIdKey); } } @Override public void destroy() { }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
注册过滤器
package com.nobody.ehr.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.nobody.ehr.filter.LogMDCFilter;
/**
* 注册日志过滤器
*
* @author Μr.ηobοdy
*
* @date 2020-04-29
*
*/
@Configuration
public class FilterConfig { @Bean public FilterRegistrationBean<LogMDCFilter> logFilterRegistration() { FilterRegistrationBean<LogMDCFilter> registration = new FilterRegistrationBean<LogMDCFilter>(); // 注入过滤器 registration.setFilter(new LogMDCFilter()); // 拦截规则 registration.addUrlPatterns("/*"); // 过滤器名称 registration.setName("logMDCFilter"); // 过滤器顺序 registration.setOrder(0); return registration; }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
返回值封装
package com.nobody.ehr.exception;
import org.slf4j.MDC;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 异常数据封装
*
* @author Μr.ηobοdy
*
* @date 2020-03-12
*
*/
@Getter
@Setter
@ToString
public class RestErrorData { private String error; private int error_code; private String error_description; private String error_uri; private String requestId = MDC.get("requestId"); public RestErrorData() { super(); } public RestErrorData(String error, int error_code, String error_description) { super(); this.error = error; this.error_code = error_code; this.error_description = error_description; } public RestErrorData(RestAPIError restAPIError) { super(); this.error = restAPIError.error; this.error_code = restAPIError.error_code; this.error_description = restAPIError.error_description; }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
logback.xml文件,其中%X{requestId}就是唯一追踪ID的值
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds"
debug="false">
<property name="filters"
value="full,$Proxy,javax.crypto.Cipher,com.sun.,sun.reflect.,java.lang.reflect.,java.io.,java.net.,org.eclipse.jetty.,org.apache.cxf.,org.springframework.beans.,org.springframework.context.,org.apache.commons.httpclient.,org.apache.commons.pool.,org.apache.http.,io.netty.,org.junit.,org.apache.maven.,org.springframework.amqp.rabbit." />
<property name="layout" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5level [%thread] [requestId-%X{requestId}] %logger{50}%n - %msg%n"/>
<property name="maxHistory" value="30" />
<property name="maxFileSize" value="50MB" />
<appender name="console"
class="ch.qos.logback.core.ConsoleAppender">
<encoder> <pattern>${layout}</pattern>
</encoder>
</appender>
<appender name="logFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>./logs/server.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>./logs/server%d{yyyy-MM-dd}_%i.log</FileNamePattern> <MaxHistory>${maxHistory}</MaxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>${maxFileSize}</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <charset>UTF-8</charset> <pattern>${layout}</pattern>
</encoder>
</appender>
<appender name="toLogFileAsync"
class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<appender-ref ref="logFile" />
</appender>
<root level="INFO">
<appender-ref ref="toLogFileAsync" />
<appender-ref ref="console" />
</root>
<!-- motan log -->
<appender name="toMotanLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>./logs/motan.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>./logs/motan.log.%d{yyyy-MM-dd}.%i </fileNamePattern> <maxHistory>${maxHistory}</maxHistory> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>${maxFileSize}</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"> <charset>UTF-8</charset> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>${layout}</Pattern> </layout>
</encoder>
</appender>
<appender name="toMotanLogAsync"
class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize></queueSize>
<appender-ref ref="toMotanLog" />
</appender>
<logger name="accessLog" level="INFO" additivity="false">
<appender-ref ref="toMotanLogAsync" />
</logger>
<logger name="serviceStatsLog" level="INFO" additivity="false">
<appender-ref ref="toMotanLogAsync" />
</logger>
</configuration>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
验证结果:
文章来源: javalib.blog.csdn.net,作者:陈皮的JavaLib,版权归原作者所有,如需转载,请联系作者。
原文链接:javalib.blog.csdn.net/article/details/105844926
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)