在SpringBoot项目中添加logback的MDC
先看下MDC是什么
Mapped Diagnostic Context,用于打LOG时跟踪一个“会话“、一个”事务“。举例,有一个web controller,在同一时间可能收到来自多个客户端的请求,如果一个请求发生了错误,我们要跟踪这个请求从controller开始一步步都执行到了哪些代码、有哪些log的输出。这时我们可以看log文件,但是log文件是多个请求同时记录的,基本无法分辨哪行是哪个请求产生的,虽然我们可以看线程,但线程可能被复用,也是很难分辨出,这时MDC就派上用场了。
我们可以加一个web filter,在请求进来时,把”标识“放到MDC context中,比如:put( ip, 8.8.8.8), put(username, 'yang'),在filter结束时把context再清掉,即可在整个请求处理过程中,都可以打印出ip, username这些数据,就可以方便的用于日志跟踪。
在SpringBoot中怎么用
- @Component
- public class LogInterceptor implements HandlerInterceptor {
- private final static String REQUEST_ID = "requestId";
- private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);
- @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();
- LOGGER.info("put requestId ({}) to logger", uuid);
- LOGGER.info("request id:{}, client ip:{}, X-Forwarded-For:{}", uuid, remoteIp, xForwardedForHeader);
- MDC.put(REQUEST_ID, uuid);
- return true;
- }
- @Override
- public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
- String uuid = MDC.get(REQUEST_ID);
- LOGGER.info("remove requestId ({}) from logger", uuid);
- MDC.remove(REQUEST_ID);
- }
- @Override
- public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
- }
- }
关键代码在于:MDC.put(REQUEST_ID, uuid);
2. 注册一下这个Interceptor,写一个WebMvcConfigurer类:
- @Configuration
- public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
- @Autowired
- private LogInterceptor logInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(logInterceptor);
- super.addInterceptors(registry);
- }
- }
- <configuration scan="true" scanPeriod="30 seconds" debug="true">
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <target>System.out</target>
- <encoder>
- <pattern>[%date{ISO8601}] [%-5level] - [%thread] [%X{requestId}] [%logger] [%X{akkaSource}] - %msg %rootException %n
- </pattern>
- </encoder>
- </appender>
- <root level="INFO">
- <appender-ref ref="STDOUT"/>
- </root>
- </configuration>
注意这个<pattern/>中配置了输出 requestId
在SpringBoot项目中添加logback的MDC的更多相关文章
- 在SpringBoot项目中添加SpringMVC拦截器
1.认识拦截器 SpringMVC的拦截器(Interceptor)不是Filer,同样可以实现请求的预处理.后处理.使用拦截器仅需要两个步骤 实现拦截器 注册拦截器 1.1实现拦截器 实现拦截器可以 ...
- 在SpringBoot中添加Logback日志处理
前言 SpringBoot项目中在官方文档中说明,默认已经依赖了一些日志框架.而其中推荐使用的就是Logback,所以这一次我将在我的模版中加入Logback日志的配置,说明一下,SpringBoot ...
- SpringBoot12 QueryDSL01之QueryDSL介绍、springBoot项目中集成QueryDSL
1 QueryDSL介绍 1.1 背景 QueryDSL的诞生解决了HQL查询类型安全方面的缺陷:HQL查询的扩展需要用字符串拼接的方式进行,这往往会导致代码的阅读困难:通过字符串对域类型和属性的不安 ...
- JAVA项目中引用Logback的方法
一.简介 本文主要讲JAVA项目中引入Logback的方法. 二.解决 1.引入依赖. <!--Begin LogBack Log--> <!-- https://mvnreposi ...
- 五分钟后,你将学会在SpringBoot项目中如何集成CAT调用链
买买买结算系统 一年一度的双十一购物狂欢节就要到了,又到剁手党们开始表演的时刻了.当我们把种草很久的商品放入购物车以后,点击"结算"按钮时,就来到了买买买必不可少的结算页面了.让我 ...
- SpringBoot项目中遇到的BUG
1.启动项目的时候报错 1.Error starting ApplicationContext. To display the auto-configuration report re-run you ...
- springboot项目中接口入参的简单校验
.katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...
- Spring-Boot项目中配置redis注解缓存
Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...
- Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作
Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 1>. 创建一个控制台程序2>. 添加一个 ADO.NET实体数据模型,选择对应的数据库与表(Studen ...
随机推荐
- 使用 MSIX 打包 DotNetCore 3.0 客户端程序
如何你希望你的 WPF 程序能够以 Windows 的保护机制保护起来,不被轻易反编译的话,那么这篇文章应该能帮到你. 介绍 MSIX 是微软于去年的 Windows 开发者日峰会 上推出的全新应用打 ...
- Uncaught ReferenceError: jQuery is not defined
页面调试时,明明引入了JQ文件,却一直提示Uncaught ReferenceError: jQuery is not defined错误. 转自:http://blog.csdn.net/baicp ...
- ArcPy 拷贝数据库
使用Python脚本进行图形数据库的拷贝. 原始帖子地址:https://www.2cto.com/database/201302/187391.html 整理Python代码: # -*- codi ...
- Android项目实战欢迎界面
欢迎界面 首先同理把欢迎界面的图片导入到drawable目录下,在导入时 Android Studio 会提示如下 drawable 具体本人尚未弄明白,待理解后会重新补全本部分内容,在此本人选了第一 ...
- 基于LinedHashMap 实现LRUCache 缓存
原文链接 基于LinedHashMap 实现LRUCache 缓存 基于LinkedHashMap实现LRUCache public class LRUCache2<K, V> exten ...
- 将对象xml序列化和反序列化
//将一个对象按XML序列化的方式写入到一个文件,使用的默认的UTF8编码格式 //o为要序列化的对象 //path保存文件的路径 public static object _lockObj=new ...
- SqlServer 操作 JSON
SqlServer 操作 JSON Intro Sql Server 从 2016 开始支持了一些 json 操作,最近的项目里也是好多地方直接用字段直接存成了 json ,需要了解一下怎么在 Sql ...
- js 学习之路9:运算符
1. 算数运算符 运算符 描述 例子 结果 + 加 x=y+2 x=7 - 减 x=y-2 x=3 * 乘 x=y*2 x=10 / 除 x=y/2 x=2.5 % 求余数 (保留整数) x=y%2 ...
- Mysql5.6二进制包安装方法
1.Download MySQL Community Server 访问mysql官方网站转到下载页https://dev.mysql.com/downloads/mysql/5.6.html#dow ...
- SQLAchemy模块
老师的博客:http://www.cnblogs.com/wupeiqi/articles/5713330.html 有一篇习详细的博客: http://www.keakon.net/2012/12/ ...