Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Springboot系列之—动态配置logback路径 #58

Open
johnnian opened this issue Mar 28, 2019 · 6 comments
Open

Springboot系列之—动态配置logback路径 #58

johnnian opened this issue Mar 28, 2019 · 6 comments
Labels

Comments

@johnnian
Copy link
Owner

场景

公司有个给客户定制的项目,有个需求是:项目中常见的配置,需要全部迁移到客户内部的 “配置中心”,然后项目启动的时候,动态从“配置中心”拉去配置,初始化:数据源、日志路径等。

项目运行环境:

  • 项目框架: Springboot
  • 运行容器: 以war包的形式,在tomcat容器下运行;

对于数据源来说,配置相对容易,但是在动态配置logback日志打印路径时,遇到一些问题,最终使用下面比较轻量的方式解决:

解决方法

1、创建 PropertyDefinerBase 类

import ch.qos.logback.core.PropertyDefinerBase;
import org.springframework.stereotype.Component;

@Component
public class LogDirConfig extends PropertyDefinerBase {
	
	//从客户的配置中心获取日志路径
	@Value("${XXXX.XXXX.logDir}")
	private String dirName;

    @Override
    public String getPropertyValue() {
        return dirName;
    }
}

2、修改logback配置文件

<configuration scan="true" scanPeriod="10 seconds">
    <include resource="org/springframework/boot/logging/logback/base.xml" />

    <define name="log.dir" class="com.config.LogDirConfig" />

    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.dir}/info.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.dir}/info-%d{yyyyMMdd}.%i.log.zip</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>2048MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>180</maxHistory>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}%line -%msg%n
            </Pattern>
        </layout>
    </appender>
    ...
    

3、修改application.properties

#日志设置
logging.config=classpath:logback-spring.xml
@xkcoding
Copy link

请问这个可以在项目启动后进行动态修改日志目录吗

@johnnian
Copy link
Owner Author

johnnian commented Sep 23, 2019

请问这个可以在项目启动后进行动态修改日志目录吗

没试过,应该是可行的,您可以参考下:

@xkcoding
Copy link

这个是在启动的时候注入的,后续好像修改不了了

@ShawshankLin
Copy link

使用@value 是需要重启的,需要手动设置environment才行

@git10135405
Copy link

请问这个可以在项目启动后进行动态修改日志目录吗

可以吗?

@natezhengbne
Copy link

打成Jar包就不行了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants