1
votes

I am trying to limit maximum number of log files using "totalSizeCap" element from logback. I am using spring boot application, so included logback as follows :

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <include resource="log4j/logback-${spring.profiles.active}.xml"/>
</configuration>

log4j/logback-DEV.xml

included>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/tmp//log/log.out</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>/tmp/log/log_%d{yyyy-MM-dd}.%i.out</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>1</maxHistory>
            <totalSizeCap>2MB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
            </pattern>
        </encoder>
    </appender>

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

    <logger name="com.company" level="INFO" />
    <logger name="org.springframework" level="ERROR" />

</included>

ERROR

ERROR in ch.qos.logback.core.joran.spi.Interpreter@17:27 - no applicable action for [totalSizeCap], current ElementPath  is [[configuration][appender][rollingPolicy][totalSizeCap]]

How I limit the log files?

1

1 Answers

0
votes

My guess is that the logback.xml isn't the right place to specify what you want. Instead you should be using the logback-spring.xml file. This is due to the fact that the Logback framework is loaded before the ApplicationContext (so that the context can log some initial things) then the context loads the logback-spring.xml to change the logback settings for the rest of the time the application is running. As such my guess is that the ${spring.profiles.active} is not replaced with the active profile.

From the reference

When possible we recommend that you use the -spring variants for your logging configuration (for example logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

Reading a bit further while answering this question there is a section specifically around Logback extensions. It looks like you need to use <springProperty> element in the configuration to expose the property.

<springProperty scope="context" name="activeProfile" source="spring.profiles.active" defaultValue="DEV"/>
<include resource="log4j/logback-${activeProfile}.xml"/>