添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

先看一张图:
在这里插入图片描述 有同学问:日志中[]中类似uuid的这个traceId是怎么实现的,这边文章就介绍下如何在springboot工程下用MDC实现日志文件中打印traceId。

1. 为什么需要这个traceId
我们在定位问题的时候需要去日志中查找对应的位置,当我们一个接口的请求同用唯一的一个traceId,那我们只需要知道这个traceId,使用 grep ‘traceId’ xxx.log 语句就能准确的定位到目标日志。在这边文章会介绍如何去设置这个traceId,而后如何在接口返回这个traceId。

#接口返回:
    "code": "0",
    "dealStatus": "1",
    "TRACE_ID": "a10e6e8d-9953-4de9-b145-32eee6aa5562"
#查询日志
 grep 'a10e6e8d-9953-4de9-b145-32eee6aa5562' xxxx.log

2.通过MDC设置traceId
笔者目前遇到的项目,可以有三种情况去设置traceId。先简单的介绍MDC

 #MDC定义
 Mapped Diagnostic Context,即:映射诊断环境。
 MDC是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能。
 MDC 可以看成是一个与当前线程绑定的哈希表,可以往其中添加键值对。
 #MDC的使用方法
 向MDC中设置值:MDC.put(key, value);
 从MDC中取值:MDC.get(key);
 将MDC中内容打印到日志中:%X{key}

2.1 使用filter过滤器设置traceId
新建一个过滤器,实现Filter,重写init,doFilter,destroy方法,设置traceId放在doFilter中,在destroy中调用MDC.clear()方法。

@Slf4j
@WebFilter(filterName = "traceIdFilter",urlPatterns = "/*")
public class traceIdFilter implements Filter {
     * 日志跟踪标识
    private static final String TRACE_ID = "TRACE_ID";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        MDC.put(TRACE_ID, UUID.randomUUID().toString());
        filterChain.doFilter(request, servletResponse);
    @Override
    public void destroy() {
    	MDC.clear();

2.2 使用JWT token过滤器的项目
springboot项目经常使用spring security+jwt来做权限限制,在这种情况下,我们通过新建filter过滤器来设置traceId,那么在验证token这部分的日志就不会带上traceId,因此我们需要把代码放在jwtFilter中,如图:

* token过滤器 验证token有效性 * @author china @Component public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private TokenService tokenService; * 日志跟踪标识 private static final String TRACE_ID = "TRACE_ID"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { MDC.put(TRACE_ID, UUID.randomUUID().toString()); LoginUser loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) { tokenService.verifyToken(loginUser); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); chain.doFilter(request, response); @Override public void destroy() { MDC.clear();

2.3 使用Interceptor拦截器设置traceId
定义一个拦截器,重写preHandle方法,在方法中通过MDC设置traceId

* MDC设置traceId拦截器 * @author china @Component public abstract class TraceIdInterceptor extends HandlerInterceptorAdapter { private static final String UNIQUE_ID = "TRACE_ID"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { MDC.put(UNIQUE_ID, UUID.randomUUID().toString()); return true; @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { MDC.clear();

3.logback.xml中配置traceId
与之前的相比只是添加了[%X{TRACE_ID}], [%X{***}]是一个模板,中间属性名是我们使用MDC put进去的。

<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" /> #增加traceId后 <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - [%X{TRACE_ID}] - %msg%n" />

4.补充异步方法带入上下文的traceId
异步方法会开启一个新线程,我们想要是异步方法和主线程共用同一个traceId,首先先新建一个任务适配器MdcTaskDecorator,如图:

public class MdcTaskDecorator implements TaskDecorator 
     * 使异步线程池获得主线程的上下文
     * @param runnable
     * @return
    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String,String> map = MDC.getCopyOfContextMap();
        return () -> {
            try{
                MDC.setContextMap(map);
                runnable.run();
            } finally {
                MDC.clear();

然后,在线程池配置中增加executor.setTaskDecorator(new MdcTaskDecorator())的设置

* 线程池配置 * @author china @EnableAsync @Configuration public class ThreadPoolConfig { private int corePoolSize = 50; private int maxPoolSize = 200; private int queueCapacity = 1000; private int keepAliveSeconds = 300; @Bean(name = "threadPoolTaskExecutor") public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); executor.setTaskDecorator(new MdcTaskDecorator()); // 线程池对拒绝任务(无线程可用)的处理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor;

最后,在业务代码上使用@Async开启异步方法即可

    @Async("threadPoolTaskExecutor")
    void testSyncMethod();

5.在接口放回中,增加traceId返回
在笔者项目中,接口返回都使用了一个叫AjaxResult自定义类来包装,所以只需要把这个类的构造器中增加traceId返回即可,相对简单。

* 日志跟踪标识 private static final String TRACE_ID = "TRACE_ID"; * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 public AjaxResult() { super.put(TRACE_ID, MDC.get(TRACE_ID)); * 初始化一个新创建的 AjaxResult 对象 * @param code 状态码 * @param msg 返回内容 public AjaxResult(int code, String msg) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); super.put(TRACE_ID, MDC.get(TRACE_ID)); * 初始化一个新创建的 AjaxResult 对象 * @param code 状态码 * @param msg 返回内容 * @param data 数据对象 public AjaxResult(int code, String msg, Object data) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); super.put(TRACE_ID, MDC.get(TRACE_ID)); if (StringUtils.isNotNull(data)) { super.put(DATA_TAG, data); 先看一张图:有同学问:日志中[]中类似uuid的这个traceId是怎么实现的,这边文章就介绍下如何在springboot工程下用MDC实现日志文件中打印traceId。1. 为什么需要这个traceId我们在定位问题的时候需要去日志中查找对应的位置,当我们一个接口的请求同用唯一的一个traceId,那我们只需要知道这个traceId,使用 grep ‘traceId’ xxx.log 语句就能准确的定位到目标日志。因为在这边文章会介绍如何去设置这个traceId,而后如何在接口的返回这个traceI
一:日志TraceId使用场景 1.1 场景一 工作根据日志排查问题时我们经常想看到某个请求下的所有日志,可是由于生产环境并发很大,每个请求之间的日志并不连贯,互相穿插,如果在打印日志时没有为日志增加一个唯一标识是没法分辨出那些日志是那个请求打印的。 1.2 场景二 在微服务场景下,我们想知道一个请求所有和该请求相关的链路日志,此时也需要为日志增加一个唯一标识。通常可以使用UUID或者其它雪花算法等作为唯一标识。 二:MDC MDC(Mapped Diagnostic Context)映射诊断环境,是
New features: Optimization of the calculation of minimum and maximum values in signal dialog Correction of a crash when copying nodes in a read-only database When exporting CSV signals, the minimum and maximum values are exported with full precision For a node's Mapped Rx signal, the assigned value table is displayed in the dialog box in addition to the overview. For user-defined attributes with the type "hex" it is now possible to define the min/max/default values also in the range 0xF0000000 to 0xFFFFFFFFFF. Correction of a slowdown when opening some MDC databases Error correction when comparing messages if they are identified by their names. Error correction when exporting databases, if CANdb++ Admin. J1939 is installed under C: \Programs 将Flogger添加到Spring Boot项目就像将依赖项添加到flogger-spring-boot一样简单。 <dependency> <groupId>com.jahnelgroup.flogger</groupId> <artifactId>flogger-spring-boot</artifactId> <version>2.0.0</version> </dependency> Java 8 Flogger也可以使用aspectj-maven-plugin在纯Java项目使用。 flogger-sample是一个示例项目,显示了如何进行设置。 要将方法参数添加到MDC,请使用@BindPar 头部信息:包括姓名、联系方式(电话号码、电子邮件等)、地址等个人基本信息。 求职目标(可选):简短描述您的求职意向和目标。 教育背景:列出您的教育经历,包括学校名称、所学专业、就读时间等。 工作经验:按时间顺序列出您的工作经历,包括公司名称、职位、工作时间、工作职责和成就等。 技能和能力:列出您的专业技能、语言能力、计算机技能等与职位相关的能力。 实习经验/项目经验(可选):如果您有相关实习或项目经验,可以列出相关信息。 获奖和荣誉(可选):列出您在学术、工作或其他领域获得的奖项和荣誉。 自我评价(可选):简要描述您的个人特点、能力和职业目标。 兴趣爱好(可选):列出您的兴趣爱好,展示您的多样性和个人素质。 参考人(可选):如果您有可提供推荐的人员,可以在简历提供其联系信息。 简历内容模板: 联系方式: 求职目标: (简短描述您的求职意