7

I want to define high-level file logging in application.properties as a convenience to leverage my log4j2.xml file configuration. By itself my log4j2 config is working fine, however I was hoping to control logging levels and log file and path info from the application.properties file. I have the spring-boot-starter-log4j2 dependency in the application's pom file.

In log4j2.xml I have as one of the properties

<Property name="LOG_FILE">${LOG-DIR}/test.log</Property>

, where LOG-DIR is defined in another (previous) property in the same file. In my application.properties file, I have

logging.file=LOG_FILE 

as a property, plus several level properties such as

logging.level.org.springframework.web=DEBUG

none of these log-related properties as defined in my application.properties file are working to build the corresponding log file. Again, when I simply use log4j2.xml by itself it works fine, but wanted to take advantage of the convenience of application.properties for logging configuration.

Any insights into what I am doing wrong are greatly appreciated. thank you

Timothy Clotworthy
  • 1,960
  • 2
  • 19
  • 42
  • In case you need different property values in log4j2.xml config for different spring profiles (dev, test, prod, etc.). You could access spring profile files like: https://stackoverflow.com/a/70471889/4768635 – MrBlack Dec 28 '21 at 08:20

1 Answers1

11

If I understood your question right, you are looking at Property Substitution feature of log4j2.

You can define logging property in application.properties file like below:

log.file.path=/myDir/logpath 

And then the property(s) lookup defined as Property in log4j2.xml:

<Configuration>  
  <Properties>  
      <property name="LOG_FILE">${bundle:application:log.file.path}</property> 
  </Properties>  

Now all the property can be referred in same log4j2.xml with ${propertyName} notation, which eventually points to values from application.properties file.

Amith Kumar
  • 4,400
  • 1
  • 21
  • 28
  • 2
    But what if I have defined logging.file.path in a YAML configuration? – Chetan Oswal Sep 29 '20 at 09:00
  • Spring Boot will automatically find and load application.properties and application.yaml files. – roottraveller Apr 05 '21 at 09:19
  • @ChetanOswal - Missed this one, yes as roottraveller already alluded. Spring supports both YML & Properties file configuration, so either with work. You can in fact have both yml & properties files under the same project with different attributes, and spring load it for you just fine. – Amith Kumar Apr 05 '21 at 15:50
  • I tried - ` ${bundle:application:logging.file.name} `. It didn't work. Got error - `Can't find bundle for base name application, locale en_US`. But I have that file in src/main/resources path. I'm using application.yml. I found that isue is only with YML file. If you use properties file, then the above works fine. I need solution for YML file. – Chetan Oswal Sep 03 '21 at 07:02