finatra
finatra copied to clipboard
MDC and Log4J2 do not get along very well
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 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.