0

I am trying to log the request id and other properties like request path from requests to the Spring webflux endpoint with RouterFunctions. The issue is when I put in the MDC information it gets lost at some point for example when making a database request with R2DBC. I was wondering what a possible solution was since none of the solutions I was able to find worked. Below is some of the code that I am using for my project:

RouterFunction code:

fun routes(
    testResource: TestResource,
    errorResource: ErrorResource
): RouterFunction<ServerResponse> = coRouter {
    filter(::filterMDC)
    filter(::filterException)
    "api".nest {
        "/v1/test/{test}".nest {
            GET("", testResource::test)
        }
    }
}

filterMDC code:

suspend fun filterMDC(request: ServerRequest, next: suspend (ServerRequest) -> ServerResponse): ServerResponse {
MDC.put(
    REQUEST_ID_MDC_PARAM,
    request.headers().firstHeader(REQUEST_ID_HEADER_NAME) ?: UUID.randomUUID().toString()
)

....

MDC.put(
    RESOURCE_MDC_PARAM,
    "${request.methodName()} ${request.uri()}"
)
return next(request)
}

testResource test code:

suspend fun test(
    serverRequest: ServerRequest
): ServerResponse {
    logger.info(
        "foo" to "bar"
    ) { "foobar" }

    val user = withContext(MDCContext()) {
        testRepository.getUser()
    }

    return ServerResponse.ok().bodyValueAndAwait(user.let(::toApiResponse))
}

TestRepository code:

class TestRepository(
    private val r2dbcEntityTemplate: R2dbcEntityTemplate
) {
    suspend fun getUser(): User {
        return r2dbcEntityTemplate
            .select<User>()
            .from("users")
            .awaitOne()
    }
}

I have tried to use MDCContext from SLF4J for coroutines but that didn't solve the issue with the MDC context being lost. Is there a good way to solve this?

MrAndre
  • 811
  • 1
  • 10
  • 26
  • 1
    MDC does not work, as it uses threadlocal which cannot be used in webflux. You need to use the reactive context. There is a chapter on it in the reactor documentation. – Toerktumlare Nov 25 '21 at 23:42
  • 1
    Does this answer your question? [How to correctly use slf4j MDC in spring-webflux WebFilter](https://stackoverflow.com/questions/51738140/how-to-correctly-use-slf4j-mdc-in-spring-webflux-webfilter) – Toerktumlare Nov 25 '21 at 23:44

0 Answers0