Skip to content

Improve the documentation and discoverability of CoWebFilter #31877

@IevgenBizz

Description

@IevgenBizz

Affects: spring-boot 3.2.0


I want to implement trace id logging for my service. But MDC context is lost in controller according to logs.

There is a filter

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class TraceIdFilter : WebFilter {

    companion object {
        val logger: Logger = LoggerFactory.getLogger(this::class.java)
    }

    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val tid = Random.nextInt(10_000)
        logger.info("TraceIdFilter started. tid $tid generated")
        MDC.put("traceId", "tid-$tid")

        logger.info("before TraceIdFilter")
        return chain.filter(exchange)
            .doFinally {
                MDC.clear()
            }
    }
}

Logs:

INFO 28207 --- [ctor-http-nio-2] c.e.mdcpoc.TraceIdFilter$Companion       [] : TraceIdFilter started. tid 9019 generated
INFO 28207 --- [ctor-http-nio-2] c.e.mdcpoc.TraceIdFilter$Companion       [tid-9019] : before TraceIdFilter
INFO 28207 --- [         task-1] c.e.mdcpoc.TestController$Companion      [] : controller method

PoC is attached. mdc-poc issue.zip
Start it and execute curl --location 'http://127.0.0.1:8080/test4'

  1. I would expect to see traceId in TestController logs. (it works for spring-boot before 3.2.0)
  2. I additionally noticed that MDC context isn't cleared after the first request and I can see the next log message with the previous traceId
    c.e.mdcpoc.TraceIdFilter$Companion [tid-9019] : TraceIdFilter started. tid 2494 generated

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)theme: kotlinAn issue related to Kotlin supporttype: documentationA documentation task

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions