logbackspring-logback

How do I print info logs only to console and info, debug and errors to file using logback?


application.properties file

logging.level.root=INFO

logback.xml configuration file

<configuration>
    <appender name="CONSOLE"
        class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%-5p] - %m%n</pattern>
        </encoder>
    </appender>
    <appender name="ROTATE_FILE_DAILY"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/application.log</file>
        <rollingPolicy
            class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logs/application-%d{yyyy-MM-dd}.log
            </fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{MM-dd-yyyy HH:mm:ss.SSS} [%-5p][%logger{0}.%M\(%line\)] - %m%n</pattern>
        </encoder>
    </appender>
    <root level="DEBUG">
        <appender-ref ref="ROTATE_FILE_DAILY" />
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

The above configuration prints only INFO to file and console. How do I print INFO to console and INFO, DEBUG and ERROR to file.


Solution

  • below is a snippet from my logback file

    <springProfile name="default">
        <root level="debug">
            <appender-ref ref="CONSOLE" />
        </root>
        <logger name="com.zaxxer.hikari.pool" additivity="false" level="warn">
            <appender-ref ref="CONSOLE"/>
        </logger>
        <logger name="org.apache.http.wire" additivity="false" level="warn">
            <appender-ref ref="FILE-ROLLING"/>
        </logger>
        <logger name="org.apache.http.conn" additivity="false" level="warn">
            <appender-ref ref="FILE-ROLLING"/>
        </logger>
    </springProfile>
    

    You can chose different appenders for different kind of logs / log levels