有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache Log4j2:每天一个日志文件,删除旧文件

我使用的是log4j 2.14.1

我想做的是有一个appender,它允许我每天有一个日志文件,但在N天后删除旧的日志(例如,我希望最多有10天的日志)

我尝试过使用DirectWriteRolloverStrategy,它看起来不错,每天创建一个日志文件,但显然无法删除旧文件,所以我的日志目录中充满了日志;maxFiles属性似乎只设置了The maximum number of files to allow in the time period matching the file pattern(请参见https://logging.apache.org/log4j/2.x/manual/appenders.html)。删除操作似乎只适用于DefaultRolloverStrategy

我的appender配置:

appender.rolling.type = RollingFile
appender.rolling.name = ROLLING
appender.rolling.filePattern = /var/log/application-%d{yyyy-MM-dd}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%d{yyyy-MM-dd'T'HH:mm:ss,SSS}{UTC}Z][%p][%C:%L] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.strategy.type = DirectWriteRolloverStrategy
appender.rolling.strategy.maxFiles = 3

有没有办法使用属性来配置该目录中日志的最大数量(或最长期限)


共 (2) 个答案

  1. # 1 楼答案

    正如拉尔夫·戈尔斯在log4j-user邮件列表中指出的那样,您需要配置一个删除操作。在the ^{} manual中搜索滚动时删除

  2. # 2 楼答案

    因此,经过一点修改,在沃尔坎和拉尔夫的帮助下,我发现删除操作也适用于DirectWriteRolloverStrategy,尽管我没有收到一段工作代码。我发现我要求的房产是这样的:

    appender.rolling.type = RollingFile
    appender.rolling.name = ROLLING
    appender.rolling.filePattern = /var/log/application-%d{yyyy-MM-dd}.log
    appender.rolling.layout.type = PatternLayout
    appender.rolling.layout.pattern = [%d{yyyy-MM-dd'T'HH:mm:ss,SSS}{UTC}Z][%p][%C:%L] %m%n
    appender.rolling.policies.type = Policies
    appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
    appender.rolling.strategy.type = DirectWriteRolloverStrategy
    appender.rolling.strategy.action.type = Delete
    appender.rolling.strategy.action.condition.type = IfFileName
    appender.rolling.strategy.action.basepath = /var/log
    appender.rolling.strategy.action.maxdepth = 1
    appender.rolling.strategy.action.condition.glob = application*.log
    appender.rolling.strategy.action.ifAccumulatedFileCount.type = IfAccumulatedFileCount
    appender.rolling.strategy.action.ifAccumulatedFileCount.exceeds = 10
    

    我将把补丁提交给doc,并将示例返回给log4j社区