Run GenericFilterBean before Logbook log

193 Views Asked by At

I have a filter that adds to MDC a correlationId that is received by my HTTP requests. See example below:

@Component
class CorrelationIdFilter : GenericFilterBean() {
    private val log = MyLogger.getLogger(this::class.java)

    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        if (request is HttpServletRequest) {
            MDC.put("correlationId", getCorrelationId(request))
        }

        chain.doFilter(request, response)
    }

    private fun getCorrelationId(request: HttpServletRequest): String {
        val correlationId = request.getHeader("x-correlation-id")
        return correlationId ?: "cid-${UUID.randomUUID()}"
    }
}

The problem is that at the moment Logbook logs the request, this filter is still not executed, which results in:

  • logbook request log (without correlationId in MDC)
  • add correlationId to MDC
  • [other logs]..

I'm using Spring Boot and logbook starter implementation("org.zalando:logbook-spring-boot-starter:2.14.0")

What I want to achieve is to have the filter executed prior to logbook log.

Any ideas?

1

There are 1 best solutions below

1
YuliyaD On

You need this filter to be invoked in the filter chain earlier than logbook logs the request.

Not sure how it works for Kotlin, but for Java we use @Order annotation on top of the filter class and specifying precedence.