In the case of a SiftingAppender setup, is there a way to reference a fallback appender when the MDC key is set to the default value?
For instance, I want to use a file appender when the MDC key is set to a value that is different than the default, but log to the console when the MDC key is set to the default value.
The only solution I see right now is to subclass the SiftingAppender class and override the append(E event) logic to fallback to a default appender if the MDC key is set to the default value.
You can filter your
SiftingAppenderand yourConsoleAppenderwith mutually exclusive conditions by using Logback filters.Example filter declarations:
Using Groovy to express the 'contains default MDC key' condition:
Using Janino to express the 'contains default MDC key' condition:
Assuming you choose the Janino filter then your appenders would be declared as follows::
Note: in the above examples I have used
mdc.get("yourMdcKey") == null/mdc.get("yourMdcKey") != nullto express this conditional: is the MDC key set to the default value?. It's likely that your default value is notnullbut perhaps some populated value, if so then you would alter the conditional statement accordingly.This approach allows you to declare a gate in front of your appenders and this gate applies the following test:
FileAppenderif the MDC key is not populated then ignore the event otherwise accept the eventSiftingAppenderif the MDC key is not populated then ignore the event otherwise accept the event