Spring Boot 2 and logback MDC with reactor
Asked Answered
E

1

7

I have an application written with spring 5 and reactor. I put in the subscriber context some information such as the user id.
Now I want to log this user id. I'm trying with MDC but if the request changes thread I lost the information. How can I resolve this question?
Is there a way to set the MDC so all log around the application, included external library, has the data I put in using the subscriber context?
I already tried what described here but and it works fine, but it doesn't solve my problem with the external library logs.

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

Epp answered 2/5, 2018 at 17:18 Comment(1)
take a look at this two-part article ndportmann.com/logging-with-context-in-spring-webfluxMutinous
A
3

Spring Cloud Sleuth provides a solution for this

You need to add the spring cloud sleuth dependency to project

To add a custom property to sleuth context, use

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

here "userId" is the key that is used to propagate the value

To propagate the "userId" key when the threads are changed, use

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

You can access the "userId" key from logback using

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> 
  <layout>
    <Pattern>%X{userId} - %m%n</Pattern>
  </layout> 
</appender>
Antiperspirant answered 31/12, 2019 at 9:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.