问题描述
我遇到了困扰我好几天的问题。 我解释:我有2个应用共享一台服务器。我称它们为appA和appB。我们使用Spring框架,并将logback用于日志记录系统。我配置了logback JNDI上下文选择器,如文档http://logback.qos.ch/manual/contextSelector.html中所述。并且我在服务器中将logback文件设置为:logback-appB.xml和logback-appA.xml。效果很好。
但是现在我们将appA迁移到spring boot,而appB停留在spring。我不知道为什么appA无法加载我在web.xml中配置的JNDI上下文名称:
<env-entry>
<env-entry-name>logback/context-name</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>appA</env-entry-value>
</env-entry>
然后我在类ch.qos.logback.classic.selector.ContextJNdiselector中调试了第54行:contextName = JNDIUtil.lookup(ctx,“ java:comp / env / logback / context-name”);结果是null。我不知道为什么,Spring引导力量会使用它们的上下文吗?
我认为也许我可以使用logging.config强制使用logback配置文件
用这些尝试
logging.config = Z:/ DEV /...../ logback-appA.xml或logging.config = file:Z:/ DEV /...../ logback-appA.xml或
logging.config = classepath:logback-appA.xml,它们都无法加载文件。在类org.springframework.boot.logging.logback.LogbackLoggingSystem的第67行中进行调试,字符串configLocation不再为null。
即使我设置了logging.config = Z:/ DEV /.../ logback-spring.xml,也无法加载il。
我认为我无法使用spring Active配置文件,因为appB不使用spring boot。
spring boot的版本是2.1.7。如果有人可以提供帮助,非常感谢。
解决方法
我遇到了同样的问题,经过几天的搜索,这个链接被证明是最有帮助的: http://rostislav-matl.blogspot.com/2013/03/renamed-logback-config-file-for-web.html
在您的 spring 初始值设定项中,您可以覆盖 onStartup 以添加自定义侦听器:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Add the customer listener to configure logback
servletContext.addListener(CustomServletContextListener.class);
super.onStartup(servletContext);
}
然后实现一个加载 logback 配置的自定义侦听器:
public class CustomServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
// Get the war/context name from this context event
String contextName = contextEvent.getServletContext().getContextPath().substring(1);
// Get the path of the logback configuration file
URL configFileURL = Thread.currentThread().getContextClassLoader().getResource("logback-" + contextName + ".xml");
// If the URL exists in the classpath
if (configFileURL != null) {
try {
// Reset the existing logger context and set the name to match the current context
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
loggerContext.setName(contextName);
// Update the logger context and configure the logger based on the configuration file
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
configurator.doConfigure(configFileURL);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}