log4j2: 如何强制滚动文件appender进行滚动?[英] log4j2: how-to force rolling file appender to roll over?

本文是小编为大家收集整理的关于log4j2: 如何强制滚动文件appender进行滚动?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

据我所知,log4j2 中的 RollingFileAppender 不会在指定时间(比如说 - 一个小时结束时)翻转,而是在超过时间阈值后到达的第一个日志事件时翻转.

有没有办法触发事件,一方面会导致文件翻转,另一方面 - 不会附加到日志(或会附加一些琐碎的东西,如空字符串)?

推荐答案

不,没有任何(内置)方法可以做到这一点.没有后台线程监控翻转时间.

编辑:您可以创建一个实现 org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy 的 log4j2 插件(有关示例代码,请参阅内置的 TimeBasedTriggeringPolicy 和 SizeBasedTriggeringPolicy 类.)

如果您配置自定义触发策略,log4j2 将检查每个日志事件是否应该触发翻转(因此在实现 isTriggeringEvent 方法时要小心以避免影响性能).请注意,要选择您的自定义插件,您需要在 log4j2.xml 文件的 Configuration 元素的 packages 属性中指定类的包.

最后,如果这对您很有效,并且您认为您的解决方案可能对其他人也有用,请考虑将您的自定义触发策略回馈给 log4j2 代码库.

本文地址:https://www.itbaoku.cn/post/1575180.html

问题描述

To my best knowledge, RollingFileAppender in log4j2 will not roll over at the specified time (let's say - at the end of an hour), but at the first log event that arrives after the time threshold has been exceeded.

Is there a way to trigger an event, that on one hand will cause the file to roll over, and on another - will not append to the log (or will append something trivial, like an empty string)?

推荐答案

No there isn't any (built-in) way to do this. There are no background threads monitoring rollover time.

EDIT: You could create a log4j2 plugin that implements org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy (See the built-in TimeBasedTriggeringPolicy and SizeBasedTriggeringPolicy classes for sample code.)

If you configure your custom triggering policy, log4j2 will check for every log event whether it should trigger a rollover (so take care when implementing the isTriggeringEvent method to avoid impacting performance). Note that for your custom plugin to be picked up, you need to specify the package of your class in the packages attribute of the Configuration element of your log4j2.xml file.

Finally, if this works well for you and you think your solution may be useful to others too, consider contributing your custom triggering policy back to the log4j2 code base.