Search code examples
javaspringspring-bootlogback

Specify a relative path in application properties spring file


I have not found any question with the same issue, but I'm sorry if the question is a duplicate.

I have this application.properties file:

## Logback
#logging.level.root=error
#logging.level.com.myapp.test=error
#logging.console=true
#logging.path=%AppData%/MyFolder/log
#logging.file=${logging.path}/logfile.log

And this is my logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] [%F:%L] - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${logging.file}</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] [%F:%L] - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.myapp.test" level="ERROR" additivity="false">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </logger>

    <root level="ERROR">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

The problem is I don't know how to specify the relative path %AppData% in my application.properties file. I want to use %AppData% or similar because the application will run on differents servers and I want to use the path: C:\Users\$USERNAME\AppData\Roaming\MyFolder\log

Is that possible?


Solution

  • Environment variables are automatically mapped into your Spring configuration. So you should be able to use them like any other configuration variable:

    # Logback
    logging.level.root=error
    logging.level.com.myapp.test=error
    logging.console=true
    logging.path=${APPDATA}/MyFolder/log
    logging.file=${logging.path}/logfile.log
    

    See Spring Boot - 24. Externalized Configuration