如何使特定库中的记录器静音

How to silence the logger from a specific library

我在我的代码中使用了一个库,它具有以下内容 logback.xml

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date - %-5p %t %-25logger{0} %F:%L %m%n</pattern>
    </encoder>
  </appender>

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

我无法控制此 .xml 文件,因为库作者拥有此文件,而我只是将她的库用作 jar 文件。

现在,当我将库用作 jar 时,我在输出中看到很多 "INFO" 语句。我想关闭这个库中记录器的输出。

我不想为我的应用程序全局关闭(或提高日志的严重性)。我只想让这个库中的日志静音。

我该怎么做?

您可以将 logback.xml 的位置指定为系统 属性,然后您可以更改它。

正如 logback 文档所说:

Specifying the location of the default configuration file as a system property

You may specify the location of the default configuration file with a system property named "logback.configurationFile". The value of this property can be a URL, a resource on the class path or a path to a file external to the application.

java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1

Note that the file extension must be ".xml" or ".groovy". Other extensions are ignored. Explicitly registering a status listener may help debugging issues locating the configuration file.


更新

要抑制来自指定包的日志,您可以在 logback.xml 中定义一个记录器。

例如要禁止来自“io.netty”包的日志,请将 添加到您的 logback.xml。

我能够解决问题。我在这里为其他人列出我的解决方案。

所以问题是我们有多个库,每个库都有自己的记录器。我们想要一些人的输出,而不是其他人的输出。我们可以通过下面的示例轻松模拟这一点

package com.abhi

import org.slf4j.LoggerFactory

object Program extends App {
   val f = new Foo()
   val b = new Bar()
   f.sayHello("Test1")
   b.sayHello("Test2")
}
class Foo {
   val logger = LoggerFactory.getLogger(classOf[Foo])
   def sayHello(name: String) : String = {
      logger.debug(s"++++++++++++ came inside Foo sayHello(${name}) +++++++++++++++++++++")
      "Hello " + name
   }
}

class Bar {
   val logger = LoggerFactory.getLogger(classOf[Bar])
   def sayHello(name: String) : String = {
      logger.debug(s"++++++++++++ came inside Bar sayHello(${name}) +++++++++++++++++++++")
      "Hello " + name
   }
}

现在假设我们想要保留 Foo 记录器的输出但不想要 Bar 记录器的输出。

我们会调整我们的logback.xml喜欢

<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <logger name="com.abhi.Foo" level="TRACE">
        <appender-ref ref="STDOUT" />
    </logger>
    <root level="off" />
</configuration>

这里我们明确地为 foo 设置一个记录器并将其级别设置为跟踪并将根设置为关闭。所有没有特定记录器的人都将进入 root 并且将无法记录任何内容。