log4jslf4jmdc

WARN StatusConsoleListener The key MDC_KEY was used in both the string and stack-valued MDC


I am using slf4j v2.0.9 and log4j v2.21.1.

The MCD log is working as expected but I am getting additionally this following warning.

WARN StatusConsoleListener The key MDC_KEY was used in both the string and stack-valued MDC.

Apart from setting the value for logging, I am also reading the MDC value to get the value so that I could pass it to the next REST request. In the log4j.xml file I am using the following patten to write the MDC value --> %X{MDC_KEY}

In the code I am using

public static final String DEFAULT_MDC_KEY = "MDC_KEY";


@Override
   protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException
   {
     try
     {
        //...
        MDC.pushByKey(DEFAULT_MDC_KEY, breadcrumbValue);
        //...
     }
     catch(Exception ex)
     {
        //... 
     }
     finally
     {
         MDC.clear();
     }
   }

In a different class I am retrieving the value if set.

 MDC.get(DEFAULT_MDC_KEY)

What could have caused the warning? Is there any way to suppress the warning?

Thanks, MH


Solution

  • TL;DR You probably want to use:

    try (MDCCloseable unused = MDC.putCloseable(DEFAULT_MDC_KEY, breadcrumbValue)) {
        try {
            ...
        } catch (Exception e) {
            ...
        }
    }
    
    

    First of all thank you for paying attention to warnings: in my experience it is a rare skill these days.

    SLF4J's MDC offers two kinds of methods:

    In order to implement these functions in the bridge between SLF4J API and Log4j API (cf. LOG4J2-3583) without extending the Log4j API, we decided to map both the context map and context deque map to the single Map<String, Object> offered by ThreadContext.

    That is why both maps are accessible through the %X{...} pattern converter.

    However, in order to prevent users from mistakenly overwriting an entire stack by using MDC.set, we issue warnings when the same key is used in both the context map and context deque map.

    To get rid of the warnings don't use the same key for methods of different groups. I would recommend using the better supported MDC.get/put/putCloseable methods.

    Remark: as far as I could check, Logback does not currently have a conversion pattern that would allow users to display the values of the context deque map. Therefore using the old methods allows you to be independent of the logging implementation.