当前位置: 首页 > article >正文

Log4j2的RollingFileAppender详解

引言

官方配置文档:https://logging.apache.org/log4j/2.x/manual/filters.html


RollingFileAppender:实现日志文件自动更新

当满足条件(日志大小、指定时间等)重命名或打包原日志文件进行归档,生成新日志文件用于日志写入。

The RollingFileAppender is an OutputStreamAppender that writes to the File named in the fileName parameter and rolls the file over according the TriggeringPolicy and the RolloverPolicy.


RollingFileAppender Parameters

Parameter NameTypeDescription
appendbooleanWhen true - the default, records will be appended to the end of the file. When set to false, the file will be cleared before new records are written.
bufferedIObooleanWhen true - the default, records will be written to a buffer and the data will be written to disk when the buffer is full or, if immediateFlush is set, when the record is written. File locking cannot be used with bufferedIO. Performance tests have shown that using buffered I/O significantly improves performance, even if immediateFlush is enabled.
bufferSizeintWhen bufferedIO is true, this is the buffer size, the default is 8192 bytes.
createOnDemandbooleanThe appender creates the file on-demand. The appender only creates the file when a log event passes all filters and is routed to this appender. Defaults to false.
createOnDemand 解决重启tomcat或者java -jar 重新运行应用程序时数据丢失的问题(参考别人还不理解)
filterFilterA Filter to determine if the event should be handled by this Appender. More than one Filter may be used by using a CompositeFilter.
fileNameStringThe name of the file to write to. If the file, or any of its parent directories, do not exist, they will be created.
filePatternStringThe pattern of the file name of the archived log file. The format of the pattern is dependent on the RolloverPolicy that is used. The DefaultRolloverPolicy will accept both a date/time pattern compatible with SimpleDateFormat and/or a %i which represents an integer counter. The pattern also supports interpolation at runtime so any of the Lookups (such as the DateLookup) can be included in the pattern.
immediateFlushbooleanWhen set to true - the default, each write will be followed by a flush. This will guarantee that the data is passed to the operating system for writing; it does not guarantee that the data is actually written to a physical device such as a disk drive.Note that if this flag is set to false, and the logging activity is sparse, there may be an indefinite delay in the data eventually making it to the operating system, because it is held up in a buffer. This can cause surprising effects such as the logs not appearing in the tail output of a file immediately after writing to the log.Flushing after every write is only useful when using this appender with synchronous loggers. Asynchronous loggers and appenders will automatically flush at the end of a batch of events, even if immediateFlush is set to false. This also guarantees the data is passed to the operating system but is more efficient.
layoutLayoutThe Layout to use to format the LogEvent. If no layout is supplied the default pattern layout of “%m%n” will be used.
nameStringThe name of the Appender.
policyTriggeringPolicyThe policy to use to determine if a rollover should occur.
strategyRolloverStrategyThe strategy to use to determine the name and location of the archive file.
ignoreExceptionsbooleanThe default is true, causing exceptions encountered while appending events to be internally logged and then ignored. When set to false exceptions will be propagated to the caller, instead. You must set this to false when wrapping this Appender in a FailoverAppender.
filePermissionsStringFile attribute permissions in POSIX format to apply whenever the file is created.Underlying files system shall support POSIX file attribute view.Examples: rw------- or rw-rw-rw- etc…

(1)SizeBased Triggering Policy:基于文件大小的滚动策略

The SizeBasedTriggeringPolicy causes a rollover once the file has reached the specified size. The size can be specified in bytes, with the suffix KB, MB, GB, or TB, for example 20MB. The size may also contain a fractional value such as 1.5 MB. The size is evaluated using the Java root Locale so a period must always be used for the fractional unit.

When combined with a time based triggering policy the file pattern must contain a %i otherwise the target file will be overwritten on every rollover as the SizeBased Triggering Policy will not cause the timestamp value in the file name to change. When used without a time based triggering policy the SizeBased Triggering Policy will cause the timestamp value to change.


<SizeBasedTriggeringPolicy size="1KB"/>

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logs</property>
        <Property name="FILE_NAME" value="practisesvr"/>
        <Property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}] [%-5level] [%thread] [%file:%line] → [%enc{%m}{CRLF}]%n"/>
    </properties>

    <appenders>
        <RollingFile name="SIZE_BASED_TRIGGERING"
                     fileName="${LOG_HOME}/${FILE_NAME}.log"
                     filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd}_%i.log.gz" createOnDemand="true">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="1KB"/>
            </Policies>
            <DefaultRolloverStrategy max="5"/>
        </RollingFile>
    </appenders>

    <loggers>
        <root level="all">
            <AppenderRef ref="SIZE_BASED_TRIGGERING"/>
        </root>
    </loggers>
</configuration>

上述模板中

  • 日志先写入practisesvr.log中,每当文件大小达到1KB时,按照在./applog/logs目录下以practisesvr_2023-04->02_1.log.gz格式对该日志进行压缩重命名并归档,并生成新的文件practisesvr.log进行日志写入。
  • filePattern属性的文件格式中%i就类似于一个整数计数器,受到<DefaultRolloverStrategy max="5"/>控制,当文件个数达到5个的时候会循环覆盖前面已归档的1-5个文件。若不设置该参数,默认为7
    在这里插入图片描述

DefaultRolloverStrategy Parameters

Parameter NameTypeDescription
fileIndexStringmax: 文件上到下为时间升序
min:文件上到下为时间降序
nomax:文件不覆盖,时间升序依次生成

参考此翻译 https://blog.csdn.net/yangb0803/article/details/111319935
minintegerThe minimum value of the counter. The default value is 1.
maxintegerThe maximum value of the counter. Once this values is reached older archives will be deleted on subsequent rollovers. The default value is 7.
compressionLevelintegerSets the compression level, 0-9, where 0 = none, 1 = best speed, through 9 = best compression. Only implemented for ZIP files.
tempCompressedFilePatternStringThe pattern of the file name of the archived log file during compression.


(2)TimeBased Triggering Policy:基于时间间隔的滚动策略

The TimeBasedTriggeringPolicy causes a rollover once the date/time pattern no longer applies to the active file. This policy accepts an interval attribute which indicates how frequently the rollover should occur based on the time pattern and a modulate boolean attribute.


TimeBasedTriggeringPolicy Parameters

Parameter NameTypeDescription
interval
间隔
integerHow often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and increment of 4 rollovers would occur every 4 hours. The default value is 1.
基于filePattern中配置的最小时间单位进行来控制归档频率,默认值为1。如:filePattern中最小时间单位为小时,如果interval=1,则1小时归档一次;如果interval=2,则2小时归档一次。
modulate
调整
booleanIndicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc. The default value is false.
默认为false。指明是否对interval进行调节,若modulate为true,会以0为开始对interval进行偏移计算。例如,最小时间粒度为小时,当前为3:00,interval为4,则后面归档时间依次为4:00,8:00,12:00,16:00
maxRandomDelay
最大随机延迟
integerIndicates the maximum number of seconds to randomly delay a rollover. By default, this is 0 which indicates no delay. This setting is useful on servers where multiple applications are configured to rollover log files at the same time and can spread the load of doing so across time.
指示随机延迟过渡的最大秒数。默认情况下,该值为0,表示没有延迟。此设置在配置了多个应用程序以同时滚动日志文件的服务器上很有用,并且可以在整个时间上分散这样做的负担。

验证1:<TimeBasedTriggeringPolicy interval="1"/>

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logs</property>
        <Property name="FILE_NAME" value="practisesvr"/>
        <Property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}] [%-5level] [%thread] [%file:%line] → [%enc{%m}{CRLF}]%n"/>
    </properties>

    <appenders>
        <RollingFile name="SIZE_BASED_TRIGGERING"
                     fileName="${LOG_HOME}/${FILE_NAME}.log"
                     filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH-mm-ss}_%i.log" createOnDemand="true">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
            </Policies>
            <DefaultRolloverStrategy max="5"/>
        </RollingFile>
    </appenders>

    <loggers>
        <root level="all">
            <AppenderRef ref="SIZE_BASED_TRIGGERING"/>
        </root>
    </loggers>
</configuration>

上述模板中

  • 日志先写入practisesvr.log中,每经过1s时(filePattern最小时间单位),按照在./applog/logs目录下以practisesvr_2023-04->02_1.log格式对该日志进行压缩重命名并归档,并生成新的文件practisesvr.log进行日志写入。

验证2:modulate="false"

filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH-mm}_%i.log"
 <TimeBasedTriggeringPolicy modulate="false" interval="3"/>
2023-04-03 01:22:05 :启动服务开始记录第一条日志

practisesvr_2023-04-03-01-24_1.log
2023-04-03 01:22:05
2023-04-03 01:24:59

practisesvr_2023-04-03-01-27_1.log
2023-04-03 01:25:00
2023-04-03 01:27:59

验证3:modulate="true"

filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH-mm}_%i.log"
<TimeBasedTriggeringPolicy modulate="true" interval="2"/>
2023-04-03 00:44:18:启动服务开始记录第一条日志

practisesvr_2023-04-03-00-45_1.log
2023-04-03 00:44:18  本日志文件:启动服务开始记录第一条日志
2023-04-03 00:45:59  本日志文件最后一条日志

practisesvr_2023-04-03-00-47_1.log
2023-04-03 00:46:00 本日志文件开始时间
2023-04-03 00:47:59 本日志文件结束时间

practisesvr_2023-04-03-00-49_1.log
2023-04-03 00:48:00 本日志文件开始时间
2023-04-03 00:49:59 本日志文件结束时间

filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH-mm}_%i.log"
<TimeBasedTriggeringPolicy modulate="true" interval="3"/>
2023-04-03 00:52:09 启动服务开始记录第一条日志

practisesvr_2023-04-03-00-53_1.log
2023-04-03 00:52:09 本日志文件:启动服务开始记录第一条日志
2023-04-03 00:53:59 本日志文件最后一条日志

practisesvr_2023-04-03-00-56_1.log
2023-04-03 00:54:00 本日志文件开始时间
2023-04-03 00:56:59 本日志文件结束时间

practisesvr_2023-04-03-00-59_1.log
2023-04-03 00:57:00 本日志文件开始时间
2023-04-03 00:59:59 本日志文件结束时间

验证4:验证小时场景

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logs</property>
        <Property name="FILE_NAME" value="practisesvr"/>
        <Property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}] [%-5level] [%thread] [%file:%line] → [%enc{%m}{CRLF}]%n"/>
    </properties>

    <appenders>
        <RollingFile name="SIZE_BASED_TRIGGERING"
                     fileName="${LOG_HOME}/${FILE_NAME}.log"
                     filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH}_%i.log"
                     createOnDemand="true">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true" interval="3"/>
            </Policies>
            <DefaultRolloverStrategy fileIndex = "nomax"/>
        </RollingFile>
    </appenders>

    <loggers>
        <root level="all">
            <AppenderRef ref="SIZE_BASED_TRIGGERING"/>
        </root>
    </loggers>
</configuration>

2023-04-03 08:56:19 启动服务开始记录第一条日志

practisesvr_2023-04-03-08_1.log
2023-04-03 08:56:19 本日志文件:启动服务开始记录第一条日志
2023-04-03 08:59:59 本日志文件最后一条日志

practisesvr_2023-04-03-11_1.log
2023-04-03 09:00:00 本日志文件开始时间
2023-04-03 11:59:59 本日志文件结束时间

如上modulate="true"设置后,假如8点56分的日志开始重启服务,日志先写入logs/app.log中则9点触发一次rollover操作,生成practisesvr_2023-04-03-08_1.log对该日志进行压缩重命名并归档,并生成新的文件practisesvr.log进行日志写入;然后,每间隔3小时,则下一次是12点触发一次rollover。


(3)Composite Triggering Policy:基于时间间隔和文件大小的滚动策略

The CompositeTriggeringPolicy combines multiple triggering policies and returns true if any of the configured policies return true.
可以理解为取下限,先满足哪个策略条件就基于哪个策略生成log文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logs</property>
        <Property name="FILE_NAME" value="practisesvr"/>
        <Property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}] [%-5level] [%thread] [%file:%line] → [%enc{%m}{CRLF}]%n"/>
    </properties>

    <appenders>
        <RollingFile name="SIZE_BASED_TRIGGERING"
                     fileName="${LOG_HOME}/${FILE_NAME}.log"
                     filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd-HH}_%i.log.gz"
                     createOnDemand="true">
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true" interval="6"/>
                <SizeBasedTriggeringPolicy size="100MB"/>
            </Policies>
            <DefaultRolloverStrategy fileIndex = "nomax"/>
        </RollingFile>
    </appenders>

    <loggers>
        <root level="all">
            <AppenderRef ref="SIZE_BASED_TRIGGERING"/>
        </root>
    </loggers>
</configuration>

上述模板中,日志先写入practisesvr.log中,每当文件大小达到100MB或者当时间间隔到达6小时(由%d{yyyy-MM-dd-HH}决定),触发rollover操作,按照在./applog/logs目录下以practisesvr_2023-04-03-11_1.log.gz格式对该日志进行压缩重命名并归档,并生成新的文件practisesvr.log进行日志写入。


http://www.kler.cn/a/5695.html

相关文章:

  • linux系统编程(3)--系统调用
  • 文章八:YOLOv5车牌识别系统的Web应用与API开发
  • Java设计模式(二十一)—— 外观模式
  • 歌德巴赫猜想数学证明
  • Leetcode.2171 拿出最少数目的魔法豆
  • element plus 语言切换组件使用
  • python——面向对象(下)
  • C 中的循环
  • Jenkins使用
  • 【计算机视觉 | 目标检测】DETR风格的目标检测框架解读
  • QT之QCamera
  • Java多态
  • 阶乘约数——蓝桥杯python组国赛题(C++、唯一分解定理)
  • 利用 Docker 搭建主从服务器
  • Spring MVC 之 ViewResolver
  • 索马里ECTN/BESC/CTN证书
  • 【新2023Q2押题JAVA】华为OD机试 - 服务依赖
  • 启动优化小结
  • UDSonLIN(ISO14229-7)诊断协议
  • tsconfig.json参数详解