Spring Boot 2和logback MDC与reactor

7
我有一个使用Spring 5和Reactor编写的应用程序。我在订阅者上下文中放置了一些信息,例如用户ID。
现在我想记录这个用户ID。我尝试使用MDC,但是如果请求改变线程,我就会丢失这些信息。我该如何解决这个问题?
是否有一种方法可以设置MDC,使得应用程序中的所有日志(包括外部库)都包含我在使用订阅者上下文时放入的数据?
我已经尝试了这里描述的方法,它可以很好地工作,但无法解决我在外部库日志中遇到的问题。

https://simonbasle.github.io/2018/02/contextual-logging-with-reactor-context-and-mdc/


1
请查看这篇由两部分组成的文章: https://ndportmann.com/logging-with-context-in-spring-webflux/ - Serhii Povísenko
1个回答

3

Spring Cloud Sleuth 提供了解决方案。

您需要将 Spring Cloud Sleuth 依赖添加到项目中。

要向 Sleuth 上下文添加自定义属性,请使用:

MDC.put("userId", userId);
ExtraFieldPropagation.set("userId", userId);

这里的 "userId" 是用于传播值的关键字。

当线程发生更改时,要传播 "userId" 关键字,请使用:

spring.sleuth.propagation-keys=userId
spring.sleuth.log.slf4j.whitelisted-mdc-keys=userId

您可以使用以下方式从logback访问“userId”键:
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> 
  <layout>
    <Pattern>%X{userId} - %m%n</Pattern>
  </layout> 
</appender>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接