Unable to get MDC fields for custom logging
SummaryUser is trying to implement a custom logging appender to send log messages to a log aggregator (that is, splunk).
User wants to capture the userID, thread and requestorID, that are currently logged in the file log appenders in prlogging.
These values are MDC fields, and so user is trying to capture them with MDC.get methods, however, the user has been unsuccessful in obtaining any value from the MDC.
Error MessagesNot Applicable
Steps to ReproduceImplement a custom appender and have the appender try to retrieve a value for MDC pegathread or userID by using any of the following methods:
String mdcValue = LogContext.get("pegathread"); --using LogContext
String mdcValue = MDC.get("pegathread"); --using MDC class
Each time the mdcValue variable is always null.
As it is a AsyncAppender, the Appender append() is called on a separate dispatcher thread.
Hence, MDC.get() returns null.
What AsyncAppender does is that it stores a copy of the MDC in the LoggingEvent when AsyncAppender.doAppend() is called on the original thread itself.
So, value of any MDC key can be fetched via event.getMDC(key).
ResolutionThe following change helps address the issue:
Object val = event.getMDC("pegathread");
Published January 31, 2017 - Updated March 9, 2017