如何在EmbeddedServletContainerCustomizer-Bean中正确配置LogbackValve以读取类路径上的文件?
现在,我有以下配置,它可以在我的本地主机上完美运行(logging.accessLogConfig: src/main/resources/logback_access_dev.xml
在application.yml中设置):
@Configuration
public class TomcatConfiguration {
@Value("${logging.accessLogConfig}")
private String accessLogConfig;
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory containerFactory =
(TomcatEmbeddedServletContainerFactory) container;
LogbackValve logbackValve = new LogbackValve();
logbackValve.setFilename(accessLogConfig);
containerFactory.addContextValves(logbackValve);
}
}
};
}
}
但是,一旦我将其作为打包的应用程序部署到服务器上,就不再可以找到该文件:
-WARN in ch.qos.logback.access.tomcat.LogbackValve[] - [src/main/resources/logback_access_dev.xml] does not exist
我也在修改
logging.accesslogConfig: classpath:logbook_access_dev.xml
,并将内容读取到一个临时文件中,但是那也不起作用:@Configuration
public class TomcatConfiguration {
private static final Logger logger = LoggerFactory.getLogger(TomcatConfiguration.class);
@Value("${logging.accessLogConfig}")
private Resource accessLogConfig;
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory containerFactory =
(TomcatEmbeddedServletContainerFactory) container;
try {
InputStream configuration = accessLogConfig.getInputStream();
File configFile = File.createTempFile(accessLogConfig.getFilename(), "tmp");
FileUtils.copyInputStreamToFile(configuration, configFile);
LogbackValve logbackValve = new LogbackValve();
logbackValve.setFilename(configFile.getAbsolutePath());
containerFactory.addContextValves(logbackValve);
}
catch (IOException e) {
logger.warn("could not read access log configuration {}", accessLogConfig);
}
}
}
};
}
}
我正在使用Spring Boot 1.2.7.RELEASE以及logback-access 1.1.3。
非常感谢您提供有关如何运行的帮助:)
最佳答案
现在通过创建自己的SpringLogbackValve解决了该问题,该SpringLogbackValve接受InputStream而不是文件名。它基本上是ch.qos.logback.access.tomcat.LogbackValve的副本,只是使用Inputstream inputStream
而不是String fileName
和以下方法:
@Override
public void startInternal() throws LifecycleException {
executorService = ExecutorServiceUtil.newExecutorService();
if (inputStream != null) {
try {
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(this);
jc.doConfigure(inputStream);
}
catch (JoranException e) {
logger.warn("failed to configure {}", inputStream);
}
}
else {
getStatusManager().add(
new WarnStatus("[" + inputStream + "] does not exist", this));
}
if (!quiet) {
StatusPrinter.print(getStatusManager());
}
started = true;
setState(LifecycleState.STARTING);
}