finatra icon indicating copy to clipboard operation
finatra copied to clipboard

MDC and Log4J2 do not get along very well

Open brisssou opened this issue 2 years ago • 1 comments

Describe the bug I cannot output MDC content in logs if the log backend is log4j2.

To Reproduce

object MyAppMain extends MyApp

class MyApp extends HttpServer with  Logging {
  override protected def configureHttp(router: HttpRouter): Unit =
      router
        .filter[LoggingMDCFilter[Request, Response]]
        .filter[TraceIdMDCFilter[Request, Response]]
        .filter[FinagleRequestScopeFilter[Request, Response]]
        .add[AController]

}

class AController @Inject() extends Controller {

  get("/go") { _: Request => {
      logger.info("hello world")
      response.ok.contentType(MediaType.PlainText).body("hello world")
    }
  }
}

With log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %X - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <!-- Info by default -->
        <Root level="info" additivity="false">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Expected behavior hello world Console log lines with the content of the MDC.

Additional context It works if I use Logback. If I remove LoggingMDCFilter from the filters chain, it works with log4j2, of course, but I'm not sure this is a very good idea.

brisssou avatar Dec 20 '22 17:12 brisssou

@brisssou For the most part Finatra is meant to work with SLF4J-API logging implementation and the MDC initialization is really only tested to work with SLF4J-API implementations.

Log4J2 is an entirely different logging subsystem, so it's not expected that the MDC integration will work out of the box with Log4J2. You may need to write your own adaptor for the MDC to propagate across Locals in Finagle if you use Log4J2.

Hope that helps.

cacoco avatar Apr 25 '23 20:04 cacoco