TimeBasedTriggeringPolicy log4j2 在新的一天发生时不会滚动

TimeBasedTriggeringPolicy log4j2 not rolling over when new day happens

我已经使用以下配置配置了 Log4j2,但 TimeBasedTriggeringPolicy 不起作用,我在旧日的日志中获取新日日志,请你帮忙。由于我为 DefaultRollOverStrategy 指定了 "nomax" 属性,因此它会根据大小正确滚动,并且还会创建任意数量的文件,只有 TimeBasedTriggeringPolicy 不起作用。它在前一天的日志文件中写入一天的日志。它确实创建了具有最新日期的新日志文件,但一些日志已登录到前一天的日志中。可能在正确命名文件时遇到问题我不知道。

  {
  "Configuration": {
    "Properties": {
      "Property": [
        {
          "name": "application",
          "value": "myapp"
        }
      ]
    },
    "Appenders": {
      "Console": {
        "name": "Console-Appender",
        "target": "SYSTEM_OUT",
        "PatternLayout": {
          "pattern": "%d{yyyy-MM-dd HH:mm:ss,SSS} ${application} %-5level %marker %t %c{5}  %msg%n"
        },
         "ThresholdFilter": { "level": "error" }
      },
      "RollingFile": [
        {
          "name": "File-Appender",
          "fileName":"${sys:log.path}/${application}.log",
          "filePattern":"${sys:log.path}/${application}-%d{yyyy-MM-dd}-%i.log",
          "PatternLayout": {
            "pattern": "%d{yyyy-MM-dd HH:mm:ss,SSS} ${application} %-5level %marker %t %c{5}  %msg%n"
          },
          "Policies": {
            "TimeBasedTriggeringPolicy": {"interval":"1", "modulate":"true" },
             "SizeBasedTriggeringPolicy": { "size": "5 KB" } 
            },
            "DefaultRolloverStrategy": {"fileIndex":"nomax"}   
        }
      ]
    },
    "loggers": {
      "logger":{
        "name": "com.mycompany",
        "level": "${sys:log.level}",
        "AppenderRef": { "ref": "File-Appender"}
      },
      "root": {
        "level": "error",
        "AppenderRef": { "ref": "Console-Appender" }
      }
    }
  }
}

CronTriggeringPolicy怎么样?这将在每天凌晨 12 点为您触发翻转:

{"CronTriggeringPolicy": {"schedule": "0 0 0,12 * * ?"}

这样一来,它就不会依赖于文件模式,并且绝对应该按照 cron 间隔滚动日志。我也不知道你是怎么确定前几天的日志被包含在翻转中的,但是请确保你的系统时间是同步的。

添加:

    "OnStartupTriggeringPolicy": {"minSize":"0"}

政策解决了问题。

来自log4j2 documentation

The OnStartupTriggeringPolicy policy causes a rollover if the log file is older than the current JVM's start time and the minimum file size is met or exceeded.

OnStartupTriggeringPolicy Parameters:

minSize: long: The minimum size the file must have to roll over. A size of zero will cause a roll over no matter what the file size is. The default value is 1, which will prevent rolling over an empty file