spring-bootlogginglog4j2

How to log application name in log4j2 by fetching name from bootstrap.yml in spring-boot?


I want to configure my log4j2.xml file to log my application name, by fetching it from bootstrap.yml. I have tried with following log4j2.xml configuration.

     <springProperty scope="context" name="springAppName" source="spring.application.name"/>

      <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${springAppName}  %c{1}        :- %m%n
        </Property>
    </Properties>

But it seems like not working. I know it is possible to do it by using mdc and filter. But I am looking for something that can directly fetch values from bootstrap.yml.


Solution

  • As of Log4j 2.13.0 a Spring Boot Lookup is available to Spring Boot applications by including the Log4j Spring Boot Support jar. With this support you should be able to do:

    <Properties>
      <Property name="LOG_PATTERN"
                value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${spring:spring.application.name} %c{1} %m%n"/>
    </Properties>
    

    Also, if desired this support also allows your log4j2.xml file to be managed by Spring Cloud Config.

    Note: Spring Boot initializes logging at least 3 times. The first time logging is initialized Spring will not yet have initialized and the Spring Lookup will not be able to retrieve anything. Log4j will still be able to retrieve its configuration from Spring Cloud Config if log4j2.component.properties has the appropriate settings (see this example) but that configuration will need to allow for the fact that the application name will be null. Otherwise, a configuration on the classpath could be used for initial startup and then the log4j2.xml in Spring Cloud Config could be used once Spring initializes.