java - 是否有一种现成的方法可以让 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 时才实际记录消息,但如果可用,我更喜欢已经制定的解决方案。
解决方案
在 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
推荐阅读
- python - Tensorflow 1.10 TFRecordDataset - 恢复 TFRecords
- python - Python 的 google-cloud-storage 中是否有与 `refFromUrl` 等价的东西?
- .net - UWP 在调试模式下编译,而不是发布模式/.NET 本机工具链 ILT0005
- angular - Cordova 语音识别在 Android 的后台模式下挂起
- arrays - 想要打印数组中的一组值
- matlab - Simulink 错误 S-Function 转义字符 \D 无效
- javascript - 当数字相加时提示它只是将数字和另一个数字放在一起
- google-apps-script - 无需手动登录即可验证 google 用户以运行 google app 脚本
- ionic-framework - 在选项卡内打开 URL - 离子
- javascript - react js如何防止方向键切换控件