'Printing Spring Application Name wrong in Multi ApplicationContext based Spring Boot application
I am working on a multi ApplicationContext based Spring Boot application. The number of ApplicationContext is created on the basis of the number of app jars present on the classpath. For example, if there are two application jars on classpath then there will be 2 NonWebApplicationContext and 1 WebApplicationContext. The springApplicationName is also assigned to each context as env property during the creation of the ApplicationContext.
The springApplicationName is being used in logback-spring.xml to distinguish the logs entry coming from which application (MS).
When the application is coming up, the springApplicationName is getting printed property in logs while loading each context.
When the whole application is up and hitting the API of one of the app, in that case, logback is printing the springApplicationName of context which was loaded at the end of the application startup. It is not switching the springApplicationName as per the context.
To assign separate bean of LoggerContext to each ApplicationContext, implemented InitializingBean and defined bean in each ApplicationContext as follows:-
public class LogBackConfigurer implements InitializingBean {
private Resource location;
public void setLocation(Resource location) {
this.location = location;
}
public void afterPropertiesSet() throws Exception {
JoranConfigurator configurator = new JoranConfigurator();
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
configurator.setContext(loggerContext);
configurator.doConfigure(location.getInputStream());
}
}
@Bean
public static LogBackConfigurer logBackConfigurer() {
LogBackConfigurer configurer = new LogBackConfigurer();
configurer.setLocation(new ClassPathResource("logback-spring.xml"));
return configurer;
}
Even changed the scope as context in logback-spring.xml.
<springProperty name="my.app.name" source="spring.application.name" scope="context"/>
<property name="app.name" value="${my.app.name}" scope="context"/>
Instead of using springApplicationName directly, I tried to assign springApplicationName into the MDC parameter (at many places to cover all context) but the scope of MDC is limited and it is not covering all the logs.
After making all the changes, I am still facing the same issue.
I am using spring boot and logback versions 2.4.6 and 1.2.10 respectively.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
