简体   繁体   中英

How can I read properties from spring application.yml and use it in my log4j2.xml

I have properties defined in application.yml and wanted to use them in my log4j2.xml file.

**application.properties**

logging:
  levels:
    com.mypackage: INFO
  appenders:
    name: rollingfile

I tried below approach but didn't work

    <Properties>
        <Property name="log-pattern">%d{ISO8601} %-5level {%thread} [%-40.40logger{39}] request_id=%X{requestId} %m%n</Property>
        <Property name="logging-level">${bundle:application:logging.levels.com.mypackage}</Property>
    </Properties>

<Loggers>       
        <Logger name="com.service" level="${logging-level}" includeLocation="true" additivity="false">
            <AppenderRef ref="${logging.appenders.name}"/>
        </Logger>
<Loggers>

Please help me out in resolving to read value.I am not able to get any working solution.

If you are using Spring Boot you can use Log4j's Spring Cloud Config Client jar which provides the Spring Lookup. Then you can code:

    <Properties>
        <Property name="log-pattern">%d{ISO8601} %-5level {%thread} [%-40.40logger{39}] request_id=%X{requestId} %m%n</Property>
        <Property name="logging-level">${spring:logging.levels.com.mypackage}</Property>
    </Properties>
    <Loggers>       
        <Logger name="com.service" level="${logging-level}" includeLocation="true" additivity="false">
            <AppenderRef ref="${spring:logging.appenders.name}"/>
        </Logger>
    <Loggers>

However, the Spring lookup will only work after Spring has initialized its environment. Spring Boot initializes logging at least 3 times and the first is prior to Spring doing anything. For that case you either need to provide default values or a different configuration just for the initial startup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM