5
votes

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/

1

1 Answers

2
votes

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>