首页 > 解决方案 > 是否有一种现成的方法可以让 Sfl4j / Logback 仅在消息更改时才记录消息?

问题描述

我的 java 应用程序依赖于 3rd 方库。这个库使用 Slf4j 记录。当库的包对应的记录器设置为INFO时,会产生这种日志:

14:20:49.736 [scheduling-1] INFO  i.i.s.m.a.m.MeterRegistryService - collectNumberOfApplications - Publishing the number of active applications '1' and disabled ones '0'.
14:20:54.739 [scheduling-1] INFO  i.i.s.m.a.m.MeterRegistryService - collectNumberOfApplications - Publishing the number of active applications '1' and disabled ones '0'.
14:20:59.742 [scheduling-1] INFO  i.i.s.m.a.m.MeterRegistryService - collectNumberOfApplications - Publishing the number of active applications '1' and disabled ones '0'.
14:21:04.745 [scheduling-1] INFO  i.i.s.m.a.m.MeterRegistryService - collectNumberOfApplications - Publishing the number of active applications '1' and disabled ones '0'.
14:21:09.748 [scheduling-1] INFO  i.i.s.m.a.m.MeterRegistryService - collectNumberOfApplications - Publishing the number of active applications '1' and disabled ones '0'.

所以我想知道是否有一些 slf4j 或 logback 内置功能,只有在消息正文与前一行相比发生变化时才会记录这一行。我知道我可能可以使用一些定制的附加程序来做到这一点,或者扩展一些已经存在的组件,跟踪某个记录器写入的前 n 条消息的哈希值,并且仅当记录器正在写入第一次出现的 a 时才实际记录消息,但如果可用,我更喜欢已经制定的解决方案。

标签: javalogginglogbackslf4j

解决方案


在 logback 中有一个开箱即用的过滤器,您可以为此使用它,称为DuplicateMessageFilter. 这会过滤掉完全重复的消息。您可以对想要的重复次数使用指定的阈值(通过allowedRepititions属性)

只需在您的 logback 配置中添加此过滤器,即可删除重复项。

logback 配置示例:

<configuration>

  <turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter" allowedRepetitions="1"/>

  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date [%thread] %-5level %logger - %msg%n</pattern>
    </encoder>
  </appender>

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

更多信息: https ://logback.qos.ch/manual/filters.html#DuplicateMessageFilter


推荐阅读