如何在Spring Boot项目中将环境属性从application.properties获取到logback.groo



尝试将application.properties/application.yml中定义的属性注入Spring Boot项目中的logback.groovy脚本。

我无法将EnvironmentApplicationContext注入groovy脚本。

有什么变通办法吗?

我不是在寻找像System.getProperty('spring.profiles.active') 这样的解决方案

src/main/resources/logback.groovy

import org.springframework.core.env.Environment
@Inject private Environment env; //this is not working. how to get env here?
println "spring.profiles.active : ${env.getProperty('spring.profiles.active')}"
appender("STDOUT", ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        pattern = "%green(%d{HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg%n"
    }
}
if(System.getProperty("spring.profiles.active")?.equalsIgnoreCase("prod")) {
    root INFO, ["STDOUT", "FILE"]
} else {
    root INFO, ["STDOUT"]
}

src/main/resources/application.yml

---
spring:
    profiles:
        active: development

logback.groovy需要尽早进行评估,因为否则加载spring配置、实例化bean等的代码无法记录任何内容。这就是@Inject无法工作的原因。

我看到两个选项:

  1. 您可以很容易地在logback.groovy中加载application.properties,但考虑spring提供的所有配置重写机制绝非易事
  2. 创建一个springbean,以编程方式更改logback配置初始化时

另一种方法是使用-Dlogback.configurationFile=/path/to/config.groovy在生产中外部化logback配置。将配置文件放在一个众所周知的位置(如/etc/my-app)可以轻松更改生产中的日志级别,而无需重新部署(甚至重新启动)。

很抱歉恢复这个线程,但由于这是我在寻找解决方案时发现的线程,我想分享一个解决方法。

我使用了自定义转换器和转换规则来提取类路径资源(即application.properties)中的属性:

在logback.groovy:中

conversionRule('springApplicationName', CustomSpringApplicationNameConverter)
def patternExpression = '%green([%d{YYYY-MM-dd HH:mm:ss.SSS}]) [%t] %highlight(%-5level) %magenta([%springApplicationName]) - %cyan(%logger{36}) -- %msg%n'

然后在所需的附加器中使用"patternExpression"

以及我的自定义转换器类(在groovy中):

class CustomSpringApplicationNameConverter extends ClassicConverter {
    @Override
    String convert(ILoggingEvent event) {
        ClassPathResource classPathResource = new ClassPathResource('application.properties')
        Properties applicationProperties = new Properties()
        applicationProperties.load(classPathResource.inputStream)
        String springApplicationName = applicationProperties.getProperty('spring.application.name')
        if (!springApplicationName) {
            System.err.println('Could not find entry for 'spring.application.name' in 'application.properties'')
        }
        springApplicationName
    }
}

最新更新