How to get Environment properties from application.properties into logback.groovy in Spring Boot project?

前端 未结 2 550
悲&欢浪女
悲&欢浪女 2021-02-14 23:48

Trying to inject properties defined in application.properties/application.yml into logback.groovy script in Spring Boot proje

2条回答
  •  失恋的感觉
    2021-02-15 00:32

    Sorry to resurrect this thread but while since this is thread is what I found while looking for a solution, I wanted to share a workaround.

    I have used a Custom converter and conversion rule to pull out properties in classpath resource (i.e. application.properties):

    In 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'
    

    and then 'patternExpression' used in desired appender

    and my custom converter class (in 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
        }
    }
    

提交回复
热议问题