Search code examples
javaspring-bootlogbackslf4jspring-logback

Logback TimeBasedRollingPolicy with spring boot


I wrote a TimeBasedRollingPolicy logback.xml, and while the log file is created succesfully, it seems to be reading it from the application.properties instead. Here is my setup:

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <appender name="ROLLING-FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${LOG_FILE}-%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="ROLLING-FILE"/>
    </root>

</configuration>

application.properties

logging.path=/path/to/log/folder/
logging.file=${logging.path}myLog
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

When I run my application, the log is successfully saved in the correct path, but only as myLog. I would want it to be appended with the date (as in the logback.xml). Note I do want to keep taking the logging.path and logging.file from the application.properties because I have multiple depending on the environment.

Thanks


Solution

  • 1) You need to set a logging.file or logging.path property, not both.
    So logging.file=/path/to/log/folder/myLog should be enough to get a myLog log file in the specified path.

    The spring boot documentation mentions that.

    2) This is the format pattern for the log rolling, not for the current log :

     <fileNamePattern>${LOG_FILE}-%d{yyyy-MM-dd}.log</fileNamePattern>  
    

    You get this format automatically for the current log file when it is rolled/archived because the time limit defined by the pattern is reached. In your case, it means everyday.