在运行时应用启动后覆盖 spring logback 路径

问题描述

我有一个使用 spring logback 进行日志记录的 spring boot 应用程序。我的应用程序正在部署在外部 tomcat 中。默认情况下,日志文件占用的路径位于 tomcat 的目录中,而不是 webapp 根子目录中。

例如:而不是在 tomcat -> logs -> app.log 内创建日志

我希望它位于 tomcat -> webapps -> spring-app -> logs -> app.log

由于路径仅在运行时已知,因此我声明了一个 logback-configuration 作为 app-logback-spring.xml 使用 springProperty 填充路径。

public class LoggingInitializer implements ApplicationContextInitializer{

    @Override
    public void initialize(ConfigurableApplicationContext appContext) {

        try {

            URI uri = appContext.getResource("/").getURI();
            File file = new File(uri);
            Map<String,Object> properties = new HashMap<>();
            properties.put("app-root.path",file.getAbsolutePath());
            properties.put("app.log.path",file.getAbsolutePath()+"/logs");
            System.out.println("props "+properties);
            MapPropertySource mapPropSrc = new MapPropertySource("custom",properties);
            appContext.getEnvironment().getPropertySources().addFirst(mapPropSrc);
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

            JoranConfigurator configurator = new JoranConfigurator();
            File configFile = new File(file.getAbsolutePath()+File.separator+"WEB-INF"+File.separator
                    +"classes"+File.separator+"app-logback-spring.xml");
            InputStream configStream = Files.newInputStream(configFile.toPath());
            configurator.setContext(loggerContext);
            configurator.doConfigure(configStream); // loads logback file
            configStream.close();


        } catch (IOException e) {
            throw new CustomException("Could not initialize application",e);
        } catch (JoranException e) {
            throw new CustomException("Error configuring logger",e);
        }

    }
}

<configuration>

    <springProperty scope="context" name="logpath" source="app.log.path"/>
    <appender name="RollingFile"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logpath}/app.log</file>

    ---
    ---
</configuration>

但是,在初始化期间,我认为无法识别日志路径。我根据在名为 logpath_IS_UNDEFINED 的 tomcat 下创建的文件夹推断它,并且 app.log 在它下面。

我设置的 app-root.path 可用于具有正确值的服务。我知道我可以在阅读之前写入 app-logback-spring.xml,但这看起来很复杂。

是不是因为在加载记录器时,spring 属性不可用是不是?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)