Global MDC value accross all modules and threads

Is it possible to set the current active spring profile in logback’s MDC across all threads?

I already implemented a AppLifecycleEventListener:

    public static final String MDC_KEY_SPRING_PROFILE = "springProfile";

    @Value("${spring.profiles.active:Unknown}")
    private String activeProfile;

    @EventListener
    public void applicationContextInitialized(AppContextInitializedEvent event) {
        MDC.put(MDC_KEY_SPRING_PROFILE, activeProfile);
    }

This works, but it puts the spring profile in the MDC only in the main thread of the core module. I understand that MDC uses ThreadLocal for this.

Any idea how I can populate every thread in every module with this information?

Hi,

I’d recommend taking a look at the usage of LogMdc class that is used to add properties to MDC. In the web module, it is used in the CubaVaadinServletService.

  1. Implement CustomVaadinServletService that extends CubaVaadinServletService

  2. In order to use CustomVaadinServletService you need to extend CubaApplicationServlet

import com.haulmont.cuba.web.sys.CubaApplicationServlet;
import com.vaadin.server.DeploymentConfiguration;
import com.vaadin.server.ServiceException;
import com.vaadin.server.VaadinServletService;

public class CustomApplicationServlet extends CubaApplicationServlet {

    @Override
    protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration)
            throws ServiceException {
        VaadinServletService service = new CustomVaadinServletService(this, deploymentConfiguration);
        if (classLoader != null) {
            service.setClassLoader(classLoader);
        }
        service.init();
        return service;
    }
}
  1. Register CustomApplicationServlet in web/WEB-INF/web.xml
<servlet>
    <servlet-name>app_servlet</servlet-name>
    <servlet-class>com.company.demo.web.sys.CustomApplicationServlet</servlet-class>
    <async-supported>true</async-supported>
</servlet>

Regards,
Gleb

1 Like

Thanks for your input @gorelov

Still I didn’t get it to work completely, but got one step further with your help. If I make progress I will comment again.