使用新的<maxfilesize> </maxfilesize>重新加载logback-spring.xml,而无需重新启动spring boot app

时间:2017-02-02 12:42:31

标签: java logging spring-boot logback

我有一个在C4-Large EC2实例上运行的spring boot应用程序,因为我们需要根据需要更改日志文件<maxFileSize>10MB</maxFileSize>的最大大小,而无需重新启动spring boot应用程序。目前,logback-spring.xml位于资源文件夹下,并在我们启动应用程序时加载。

2 个答案:

答案 0 :(得分:0)

如果可能的话,我建议不要使用日志记录扩展(即使用logback.xml而不是logback-spring.xml),as it does not support configuration scanning

在可以使用-Dlogback.configurationFile=/path/to/config.xml指定的外部位置(不在jar中)使用常规logback.xml文件,您应该能够利用logback的configuration scanning,例如: <configuration scan="true" scanPeriod="30 seconds">

通过这种方式,您可以在不重新启动应用程序的情况下对logback.xml进行更改(例如更新的最大文件大小)。

答案 1 :(得分:0)

经过多次尝试,我能够实现目标 -

<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${xyz.log.fsize}</maxFileSize>

此处${xyz.log.fsize}系统属性,因此为了重新加载 logback-spring.xml 而不重新启动spring boot应用,我创建了一个发布电话 -

    @PostMapping("/changeSize/{size}")
        public void fsize(@PathVariable("size") String size, HttpServletResponse response) {

            try {
                System.setProperty("xyz.log.fsize", size);
                LOG.info("Change in file size is observed reloading the loggers with the latest configs...");
                InputStream logConfStream = MQConsumerController.class.getResourceAsStream(File.separator
                        + LOGBACK_SPRING_XML);
                String logConfString = CharStreams.toString(new InputStreamReader(logConfStream));
                LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
                JoranConfigurator configurator = new JoranConfigurator();
                configurator.setContext(context);
                context.reset();
                configurator.doConfigure(new ByteArrayInputStream(logConfString.getBytes()));
                LOG.info("file size updated to -> {}", size);
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (Exception e) {
                LOG.error("Error while changing the logs file size {}", e);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

        }

现在,当您启动应用程序时,请使用VM参数-Dxyz.log.fsize=10MB

启动它

一旦应用程序启动并运行,请进行帖子调用 -

http://localhost:8080/changeSize/100MB
瞧,瞧!您的 logback-spring.xml 会在不启动应用的情况下即时重新加载。