在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 ...
随机推荐
- IntelliJ IDEA下如何设置JSP模板
今天在学习Spring MVC知识时,发现自己所用的IntelliJ IDEA中自动生成的JSP文件不支持EL表达式的使用,所以就想导入新的JSP模板,方便以后使用.根据旧模板的提示,如下图 找到Se ...
- Java 工厂模式(一)— 抽象工厂(Abstract Factory)模式
一.抽象工厂模式介绍: 1.什么是抽象工厂模式: 抽象工厂模式是所有形态的工厂模式中最为抽象和最具有一般性的一种形态,抽象工厂模式向客户端提供一个接口,使得客户端在不知道具体产品的情类型的情况下,创建 ...
- about-php
鉴于本人收集的php资料多,感觉查询起来不怎么方便.特意在github上建立了一个分支:about-php 主要是介绍围绕php的相关资料,包括php入门知识,php框架,开发工具,php项目,php ...
- 使用Navicat快速生成MySQL数据字典
1.通过information_schema.COLUMNS表 查询该表可得到所需字段信息 SELECT * FROM information_schema.COLUMNS; 如下图所示: 2.示例 ...
- 做嵌入式,C语言相关的朋友不要错过
前言 相对来讲嵌入式相关的人群总体来说比较少,那么有没有一个聚集地呢? 为回馈读者,「编程珠玑」与「嵌入式linux」,「EmbeddDeveloper」三个公众号联合组织了此次福利活动,「编程珠玑」 ...
- June. 25th 2018, Week 26th. Monday
Change in all things is sweet. 有改变就会有美好. From Aristole. Change is always good, but embracing change ...
- QGridLayout
Help on class QGridLayout in module PyQt5.QtWidgets: class QGridLayout(QLayout) | QGridLayout(QWidg ...
- Python--day05(数字、字符串、列表)
1.数字类型 1. 整型 int long(py2) 2. 小数 float 3. 布尔 bool 4. 复数 complex 2. 字符串类型 只能存一个值,是有序的不可变类型 2. ...
- PHP实现部分字符隐藏
/** * 隐藏部分字符串 * # 此方法多用于手机号码或身份证号.银行卡号的中间部分数字的隐藏 */ function func_substr_replace($str, $replacement ...
- Divisibility by 25 CodeForces - 988E (技巧的暴力)
You are given an integer nn from 11 to 10181018 without leading zeroes. In one move you can swap any ...