Logback: how to log only errors to file

蓝咒 提交于 2020-05-09 19:51:25

问题


I've been reading the logback manual for 2 hours and still can't figure how to do what I need.

It is as simple as the title says: I want to log only the errors to a file, and the other levels (including ERROR) to console.

This is the root section of my logcat.xml file:

    <root level="TRACE" >
        <appender-ref ref="CONSOLE_APPENDER" />
        <appender-ref ref="FILE_APPENDER" />
    </root>

The problem with this configuration is that it logs every level >= TRACE to both appenders.

I could let the root with only console, and define a file logger:

    <logger name='file_logger' level='ERROR' >
        <appender-ref ref="FILE_APPENDER" />
    </logger>

But then I'd have to call the normal logger like this:

LoggerFactory.getLogger(ClientClass.class);

And the file logger like this:

LoggerFactory.getLogger("file_logger");

I don't wan't to choose the logger for each class. I just want to get the root logger from the factory using the class as parameter, and have it do the correct thing depending on the level.

Is this possible?


回答1:


Put this into your file appender definition:

    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>ERROR</level>
    </filter>

The ThresholdFilter is in logback-classic.jar.




回答2:


I don't understand why wrong answer here is upvoted. The guy wants ONLY error messages in his file.

Here is the correct answer:

<filter class="ch.qos.logback.classic.filter.LevelFilter">
  <level>INFO</level>
  <onMatch>ACCEPT</onMatch>
  <onMismatch>DENY</onMismatch>
</filter>

Reference: https://logback.qos.ch/manual/filters.html#levelFilter




回答3:


Refer below code:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>


来源:https://stackoverflow.com/questions/19689223/logback-how-to-log-only-errors-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!