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/

greybeard
  • 2,249
  • 8
  • 30
  • 66
Luca
  • 321
  • 1
  • 3
  • 16

1 Answers1

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>
ashanshamika
  • 137
  • 4