Package-specific logging levels for different Logb

2020-04-02 09:52发布

问题:

I have this simple Logback config file, containing two appenders and some custom logging levels based on package name.

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

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%date{HH:mm}\t%-5level\t%msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>my_logger.log</file>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%date{dd MMM HH:mm}|%class{0}|%-5level|%msg%n</pattern>
        </encoder>
    </appender>

    <!-- custom logging levels -->
    <logger name="myapp.package1" level="INFO" />
    <logger name="myapp.package2" level="INFO" />

    <root>
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

With this configuration, the custom logging levels are applied for both appenders.

How can I change it so that only ConsoleAppender uses these custom logging levels, while FileAppender sticks to default levels?

回答1:

If you don't want to implement a custom filter, you can create a new appender with a fixed threshold (in you case INFO):

<appender name="INFO_CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    ...
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>INFO</level>
    </filter>
</appender>

Then, for your custom logging levels add the INFO_CONSOLE and your FILE appender. The additivity="false" attribute prevents the logger from logging to the CONSOLE appender inherited from root.

<logger name="myapp.package1" additivity="false">
    <appender-ref ref="INFO_CONSOLE" />
    <appender-ref ref="FILE" />
</logger>

This should log DEBUG and above to the FILE and CONSOLE appenders, except for myapp.package1 which will only log INFO and above to CONSOLE.