52

我很高兴将 SLF4J 与 logback 一起使用,并为ROOT记录器使用2 个附加程序。

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

我们如何为两个 appender 设置不同的日志级别?我仍然需要所有 ROOT-logger 消息。

  • STDOUT 的DEBUG级别
  • FILE 的INFO级别

所有日志都需要成为输出的一部分(因此需要 ROOT 记录器)。

4

2 回答 2

60

You will not ever have more than one root-logger, so your question is a bit misleading. What you are looking for is how to fine-tune which events each of the appenders does log.

And for that, you add a ThresholdFilter to each of the appenders:

http://logback.qos.ch/manual/filters.html#thresholdFilter

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

Configure level INFO for the FILE-appender and DEBUG for STDOUT.

Edit: I have to dispute the other answer's charge that this one is wrong: Yes, you can have more than one root-element in the configuration. That does not create more than one root-logger though, which was what the question's title asks for. Also, the logback manual states under http://logback.qos.ch/manual/configuration.html#syntax (highlighting mine):

Nevertheless, the very basic structure of the configuration file can be described as, < configuration > element, followed by zero or more < appender > elements, followed by zero or more < logger > elements, followed by at most one < root > element.

It might work, but at the very least it's against convention.

于 2013-09-16T12:27:04.660 回答
1

您可以有多个root元素,每个元素都有一个关联的日志记录level和一个appender-ref(我正在使用 logback.version> 1.0.13)在这种情况下,您还必须在您的附加程序中放置一个 FILTER,如下所示:

<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
    <resetJUL>true</resetJUL>
</contextListener>

<!-- To enable JMX Management -->
<jmxConfigurator/>

<appender name="console-info" class="ch.qos.logback.core.ConsoleAppender">
   <filter class="ch.qos.logback.classic.filter.LevelFilter">
     <level>INFO</level>
     <onMatch>ACCEPT</onMatch>
     <onMismatch>DENY</onMismatch>
  </filter>
  <encoder>
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
  </encoder>
</appender>  

<appender name="console-debug" class="ch.qos.logback.core.ConsoleAppender">
  <filter class="ch.qos.logback.classic.filter.LevelFilter">
     <level>DEBUG</level>
     <onMatch>ACCEPT</onMatch>
     <onMismatch>DENY</onMismatch>
  </filter>
  <encoder>
      <pattern>[%d{ddMMMyyyy HH:mm:ss.SS}]%-5level %logger{45} - %msg %n</pattern>
  </encoder>
</appender>


<root level="info">
    <appender-ref ref="console-info"/>
</root>
<root level="debug">
    <appender-ref ref="console-debug"/>
</root>

于 2014-01-29T11:38:02.097 回答