How to return MDC "inheritance" using a modern magazine?

Returning to an earlier project and turning around updating its dependencies, I had to understand that logback no longer applies MDC to children from the version 1.1.5: https://github.com/qos-ch/logback/commit/aa7d584ecdb1638bfc4c7223f4a5ff92d5ee6273

This change makes most magazines almost useless.

Although I can understand the arguments given in the related issues, I cannot understand why this change could not be made in more backward compatibility (usually usually in java ..).

Q : What is the correct way to achieve the same behavior now, besides having to subclass everything from Runnables to Threads?

+6
source share
1 answer

I do not see a direct way to change this. Two alternatives that come to mind are the following:

Method number 1: Wrap all Runnables

Imagine an abstract class that will copy MDCfrom the original Threadto the new Threadand use it insteadRunnable

public abstract class MdcAwareRunnable implements Runnable
{
    private Map<String, String> originalMdc;

    public MdcAwareRunnable()
    {
        this.originalMdc = MDC.getCopyOfContextMap();
    }

    @Override
    public void run()
    {
        MDC.setContextMap(originalMdc);
        runImpl();
    }

    protected abstract void runImpl();

    /**
     * In case some Runnable comes from external API and we can't change that code we can wrap it anyway.
     */
    public static MdcAwareRunnable wrap(Runnable runnable)
    {
        return new MdcAwareRunnable()
        {
            @Override
            protected void runImpl()
            {
                runnable.run();
            }
        };
    }
}

If some Runnablecomes from an external API that you cannot change this code, use a wraphelper method.

Disadvantage: you need to analyze and modify the entire code.

Method number 2: mess with internal components slf4j

LogbackMDCAdapter, InheritableThreadLocal - . - , MDC.mdcAdapter . , , , №1.

. LogbackMDCAdapter . . LoggingEvent.java LogbackMDCAdapter.getPropertyMap .

№ 3: ( )

, .

LogbackMDCAdapter, , .class logback.jar.

LogbackMDCAdapter , .class org.slf4j.impl.StaticMDCBinder logback.jar , LogbackMDCAdapter logback.jar, . MDC , MDCAdapter .

ClassLoader, org.slf4j.impl.StaticMDCBinder , logback.jar. : , , -, ClassLoaders.

+3
source

Source: https://habr.com/ru/post/1016081/


All Articles