When buffering ILoggingEvent log events, the RetainingAppender does not persist the event's lazily-initialized fields, such as the MDC (Mapped Diagnostic Context) and thread name. As a result, when the retained logs are eventually dumped, these fields are initialized to the current context rather than the context at the time the log event was created. This behavior leads to incorrect log information, which can cause confusion and misinterpretation of log data.
Steps to Reproduce:
Configure Logback with a RetainingAppender that buffers log events and pipes/dumps them to an Appender that does not invoke ILoggingEvent#prepareForDeferredProcessing.
1.1. Alternative: Since it is easiest to test with a ConsoleAppender, which does prepare the event for deferred processing, another way to reproduce the issue is to only log events whose level is below the threshold and finally trigger an event that dumps the buffer.
Log multiple entries while updating the MDC between each log.
Trigger an event that causes the RetainingAppender to flush the buffered logs.
Result: The flushed log events will incorrectly reflect the current MDC context rather than the context at the time each event was logged.
I will provide a test case in the upcoming PR that reproduces this issue.
Description
When buffering
ILoggingEvent
log events, theRetainingAppender
does not persist the event's lazily-initialized fields, such as the MDC (Mapped Diagnostic Context) and thread name. As a result, when the retained logs are eventually dumped, these fields are initialized to the current context rather than the context at the time the log event was created. This behavior leads to incorrect log information, which can cause confusion and misinterpretation of log data.Steps to Reproduce:
RetainingAppender
that buffers log events and pipes/dumps them to anAppender
that does not invokeILoggingEvent#prepareForDeferredProcessing
. 1.1. Alternative: Since it is easiest to test with aConsoleAppender
, which does prepare the event for deferred processing, another way to reproduce the issue is to only log events whose level is below the threshold and finally trigger an event that dumps the buffer.RetainingAppende
r to flush the buffered logs. Result: The flushed log events will incorrectly reflect the current MDC context rather than the context at the time each event was logged.I will provide a test case in the upcoming PR that reproduces this issue.
Solution
Invoke [
ILoggingEvent#prepareForDeferredProcessing()
](https://logback.qos.ch/apidocs/ch.qos.logback.classic/ch/qos/logback/classic/spi/LoggingEvent.html#prepareForDeferredProcessing()) before buffering the log event. According to the documentation, this method should be called to ensure context data like MDC and thread name are properly captured for asynchronous or deferred logging.