5

TimeBasedRollingPolicy我正在从Log4J Extras设置一个,但我不清楚什么告诉策略何时翻转。 API不是明确的,所以我只是在做推论。听起来它FileNamePattern是决定频率的最后一个元素。

log4j Wiki中的这个例子为例:

<appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">
    <!-- The active file to log to -->
    <param name="file" value="/applogs/myportal/portal.log" />
    <param name="append" value="true" />
    <param name="encoding" value="UTF-8" />

    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
    <!-- The file to roll to, this is a fairly intelligent parameter, if the file
         ends in .gz, it gzips it, based on the date stamp it rolls at that time, 
         default is yyyy-MM-dd, (rolls at midnight)
    -->
        <param name="FileNamePattern" value="/applogs/myportal/portal.%d.log.gz" />
    </rollingPolicy>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
    </layout>
</appender>

我是否假设因为模式以 结尾dd,所以策略是在变化时滚动?与 API 中的示例相同,yyyy-MM表示文件在更改时应该滚动的模式MM

谢谢!

保罗

4

2 回答 2

4

Well, I'd have to double check, but I'd say whenever the String produced by formatting the current date with the format string changes, the file is rolled. This means: if you format the date using "yyyy-MM-dd" the result would change every day. This would also happen with "dd" only, BUT you'd get the same filename every month, thus the files are either overwritten, be appended to or the rolling fails because the file already exists (not sure which is true, depends on what the appender does, I guess in this case logs will be appended, except maybe for the gzip way).

Edit:

Example: if you have mylog.%d{dd}.log, the resulting log file for today (2011-03-27) have the name mylog.25.log (due to formatting new Date() when logging) and would append messages to that file. Tomorrow, the now used file would have the name mylog.26.log. In April 25th you'd again get filename `mylog.25.log thus all logs from that day would be appended to the file which already contains logs from March 25th.

于 2011-03-25T15:24:46.633 回答
2

我得到了这个工作。下面是 log4j 的代码。您只需要在 pom.xml 中添加 log4j-extras 依赖项并使用以下代码: 下面的代码每分钟滚动一次并创建 .zip 文件。

<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">    
    <param name="FileNamePattern" value="/opt/app/srdotcom/logs/portal.%d{yyyy-MM-dd-HH-mm}.log.zip" />
</rollingPolicy>

<layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{YYYY-MM-dd HH:mm:ss:SSS z}| %c{2}| %m%n" />
</layout>

Maven依赖:

  <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>apache-log4j-extras</artifactId>
        <version>1.2.17</version>
    </dependency>
于 2017-07-06T14:23:12.630 回答