[英]Deleting log4j2 logs with DefaultRolloverStrategy not working
我正在使用log4j2
版本2.13.3
,我試圖在應用程序啟動時刪除舊日志。 我嘗試了各種示例,它們甚至沒有觸發我的DefaultRolloverStrategy
。 我實現了這樣的配置:
<properties>
<property name="filePattern">${date:yyyy-MM-dd}</property>
<Property name="baseDirectory">logs</Property>
</properties>
<Appenders>
<!-- ... -->
<RollingFile name="RollingFile" append="true" fileName="${baseDirectory}/${filePattern}.log"
filePattern="${baseDirectory}/%d{yyyy-MM-dd}.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy/>
</Policies>
<DefaultRolloverStrategy>
<Delete basePath="${baseDirectory}" maxDepth="1">
<IfFileName glob="*.log"/>
<IfLastModified age="10d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<OnStartupTriggeringPolicy/>
實際上在啟動時觸發了我的DefaultRolloverStrategy
但隨后符合條件的文件結果為空:
因此,沒有刪除任何日志,但我相當有信心我的配置是正確的。 如果我的日志文件模式與他們奇怪的PATTERN_COUNTER
常量不匹配,我是否遺漏了什么或者為什么getEligibleFiles()
方法會中止?
getEilligleFiles 考慮的場景是根據 DefaultRolloverStrategy 上指定的規則確定要刪除哪些文件。 該策略僅刪除當前時間模式的時間范圍內的文件。 例如,如果您每小時滾動一次,它只會清除當前小時內的文件。 這實際上是刪除操作的原因 - 大多數人希望刪除整個目錄或一組目錄中的文件,而不僅限於當前“窗口”。
“奇怪的 PATTERN_COUNTER 常量”用於檢查文件名中表示為 %[0]n[n...]i 的計數器。 該模式導致計數器的長度固定並帶有前導零。 您沒有使用 SizeBasedTriggeringPolicy ,因此文件模式中沒有 %i ,因此它不會匹配。
換句話說,這段代碼沒有做任何事情,因為它不適用於您的配置。
查看 DefaultRolloverStrategy 時,您可以看到它的構建器接受自定義操作。 這些是在配置期間添加的,如果您啟用了 -Dlog4j2.debug 或在 Log4j2 配置文件的 Configuration 元素上設置了 status=DEBUG,您應該能夠看到它們。 您還會注意到它們被添加到 rollover 方法末尾的 RolloverDescription 中。 這將傳遞回 RollingFileManager
if (success && descriptor.getAsynchronous() != null) {
LOGGER.debug("RollingFileManager executing async {}", descriptor.getAsynchronous());
asyncExecutor.execute(new AsyncAction(descriptor.getAsynchronous(), this));
releaseRequired = false;
}
接近翻轉方法的結尾。 這將導致刪除操作將在每次翻轉結束時作為異步任務啟動。
同樣,啟用 -Dlog4j2.debug 或設置 status=Debug 應該允許您看到這些調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.