我有一个用弹簧5和电抗器编写的应用程序。我在订户上下文中放入了一些信息,例如用户ID。现在我要记录此用户ID。我正在尝试使用MDC,但是如果请求更改了线程,我就会丢失信息。我该如何解决这个问题?有没有一种方法可以设置MDC,以便所有在应用程序周围记录的日志(包括外部库)是否可以使用订户上下文输入数据?我已经尝试过这里描述的内容,但是效果很好,但是它不能解决外部库日志的问题。
https://simonbasle.github.io/2018/02/contextual-logging-with-reactor-context-and-mdc/
Spring Cloud Sleuth为此提供了解决方案
您需要将spring cloud sleuth依赖项添加到项目中
要在侦探上下文中添加自定义属性,请使用
MDC.put("userId", userId);
ExtraFieldPropagation.set("userId", userId);
这里“ userId”是用于传播值的键
要在更改线程时传播“ userId”键,请使用
spring.sleuth.propagation-keys=userId
spring.sleuth.log.slf4j.whitelisted-mdc-keys=userId
您可以使用以下方式从登录后访问“ userId”键:>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<layout>
<Pattern>%X{userId} - %m%n</Pattern>
</layout>
</appender>