gpt4 book ai didi

spring-mvc - Spring Boot - 部署为 WAR 时从 WEB-INF/文件夹加载 'logback.xml'

转载 作者:行者123 更新时间:2023-12-01 01:58:44 25 4
gpt4 key购买 nike

我正在将传统的 Spring MVC 应用程序更新为 Spring Boot(部署为 WAR)。

一项要求是,为了保持与我们的远程安装的兼容性,logback.xml文件需要位于已部署的 webapp 中的以下位置:
webapp/WEB-INF/logback.xml
在项目源中,如果我把文件放在 src/main/webapp/WEB-INF/logback.xml ,成功复制到webapp/WEB-INF/logback.xml ,但我无法找到一种方法来加载它并从该位置使用它。

我试过设置 Spring Boot logging.config属性如下:

logging.config=/WEB-INF/logback.xml

希望自动配置能够解决它,但这会失败而不会出现错误消息,而是会加载默认的 Spring Boot 日志配置。

使用 Spring Boot 处理此问题的正确方法是什么? (欢迎使用示例代码)

最佳答案

事实证明这需要破解:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}

// In case of regular deployments, use WEB-INF/logback.xml
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
configureLogging(servletContext);
LoggerFactory.getLogger(getClass()).info("Done configuring");
}

// manually configure logging
private void configureLogging(final ServletContext servletContext) {
try {
String realPath = servletContext.getRealPath("/WEB-INF/logback.xml");
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(realPath);
} catch (JoranException je) {
// StatusPrinter will handle this
}
}

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}

}

另外,我有 logback-spring.xml src/main/resources :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="logback-include.xml" />
</configuration>

logback-include.xml src/main/resources ,它有一些常见的配置:
<?xml version="1.0" encoding="UTF-8"?>
<included>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />

<!-- put your loggers here -->
<logger name="org.springframework.web" additivity="false" level="INFO">
<appender-ref ref="CONSOLE"/>
</logger>

<!-- put your root here -->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</included>

最后, src/main/webapp/WEB-INF 中的 logback.xml像 logback-spring.xml 一样导入通用配置:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="logback-include.xml" />
</configuration>

关于spring-mvc - Spring Boot - 部署为 WAR 时从 WEB-INF/文件夹加载 'logback.xml',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com