Skip to content

Context Propagation not working for Threadlocals like MDC #5091

@mnembrini

Description

@mnembrini

Hello,

I have a project with Spring data MongoDB (reactive) and Project Reactor. I want to use the MDC for my logging. It works in a reactive chain until the first call to a MongoDB, then it disappears.

According to what I have read on online docs , it's enough to set this

spring:
  reactor:
    context-propagation: auto

and add a ThreadLocalAccessor to the ContextRegistry. Sample code:

     @GetMapping("/path/{id}")
    fun trigger(@PathVariable id: String): Mono<Unit> {


        MDC.put(KEY, id)
        MyMDC.INSTANCE.set("some value")

        val a = Car(id, "hi")

        log.info("Id start ${MDC.get(KEY)} ")

        return Mono.just(1)
            // make sure we do some thread switch
            .delayElement(Duration.ofSeconds(1))
            .flatMap {
                log.info("Id before ${MDC.get(KEY)} ")
                log.info("Custom before ${MyMDC.INSTANCE.get()} ")
                // This call is where the issue happens -> Context is not propagated correctly
                // If you comment out this flatmap, the follow one works ok
                reactiveMongoTemplate.insert(a)
            }
            .flatMap {
                // We expect here to still have the right values -> instead it's null
                log.info("Id after ${MDC.get(KEY)} ")
                log.info("Custom after ${MyMDC.INSTANCE.get()} ")
                Mono.just(Unit)
            }

    }

In the flatmap after the call to insert, the MDC is wrong (not propagated). I would expect it to have the same value as before the call to insert.
If I remove the call to insert everything works as expected.

Full example project attached (kotlin, Spring boot, maven). You need a local MongoDB instance on the default port, DB is named "test"

spring-data-context-propagation.zip

OS: Windows 10
Java: 21

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions