【Springboot之搜索日志妙招】在日志上打印请求唯一log标识

在每次请求中打出的每条日志中添加统一的请求唯一标识。通过搜索日志唯一标识,这样就可以非常高效
精准排查问题;例如:

2018-12-21 10:21:26.329 [http-nio-8080-exec-2] [my-server-logtag] [] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms 
2018-12-21 10:21:26.363 [http-nio-8080-exec-2] [my-server-logtag] [aed35d43-3fa2-46e1-bb72-ce9f50c3fe4d] ERROR com.code3.modules.controller.MyController - 日志1 
2018-12-21 10:21:26.367 [http-nio-8080-exec-2] [my-server-logtag] [aed35d43-3fa2-46e1-bb72-ce9f50c3fe4d] ERROR com.code3.advice.GlobalExceptionHandler - 系统异常,{} 
com.code3.base.BusinessException: 异常信息1
    at com.code3.modules.controller.MyController.logtag(MyController.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at 

通过日志标识:aed35d43-3fa2-46e1-bb72-ce9f50c3fe4d,就可以精准定位

原创:https://www.jianshu.com/p/b74ade8bbb57

目录

  • 自定义日志标识生成拦截器
  • 使用日志标识生成拦截器
  • 演示

自定义日志标识生成拦截器LogInterceptor

package com.interceptors.logtag.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>日志拦截器</p>
 *
 * @author zetting
 * @date 2018/8/27 11:18
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    /**
     * 日志跟踪标识
     */
    private static final String TRACE_ID = "TRACE_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = UUID.randomUUID().toString();
        if (StringUtils.isEmpty(MDC.get(TRACE_ID))) {
            MDC.put(TRACE_ID, traceId);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        MDC.remove(TRACE_ID);
    }
}

使用日志标识生成拦截器

1.在WebMvc配置加上LogInterceptor

package com.interceptors.logtag.configuration;

import com.interceptors.logtag.interceptor.LogInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * MVC配置
 *
 * @author zet
 * @date 2018-12-21 22:30
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Autowired
    private LogInterceptor logInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor);
    }
}

2.在logback文件加上[%X{TRACE_ID}]

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <jmxConfigurator/>

    <property name="app-name" value="my-server" />
    <property name="filename" value="server" />
    <property name="module-name" value="logtag" />

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [${app-name}-${module-name}] [%X{TRACE_ID}] %highlight(%-5level) %cyan(%logger{50}) - %highlight(%msg) %n</pattern>
        </encoder>
    </appender>

    <appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/data/log-center/${app-name}/${module-name}/${filename}.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>/data/log-center/${app-name}/${module-name}/${filename}.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>[%date{ISO8601}] [%level] %logger{80} [%thread] [${app-name}-${module-name}][%X{TRACE_ID}] ${app-name}-${module-name} ==> %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO" additivity="false">
        <appender-ref ref="fileAppender"/>
        <appender-ref ref="consoleAppender"/>
    </root>
</configuration>

演示

gitee源码:
https://gitee.com/zetting/my-gather/tree/master/springboot-interceptors-logtag

来源:https://www.jianshu.com/p/b74ade8bbb57
posted @ 2022-09-22 23:32  程序员小明1024  阅读(265)  评论(0编辑  收藏  举报