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 Name Type Description
append boolean When 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.
bufferedIO boolean When 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.
bufferSize int When bufferedIO is true, this is the buffer size, the default is 8192 bytes.
createOnDemand boolean The 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 重新运行应用程序时数据丢失的问题(参考别人还不理解)
filter Filter A Filter to determine if the event should be handled by this Appender. More than one Filter may be used by using a CompositeFilter.
fileName String The name of the file to write to. If the file, or any of its parent directories, do not exist, they will be created.
filePattern String The 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.
immediateFlush boolean When 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.
layout Layout The Layout to use to format the LogEvent. If no layout is supplied the default pattern layout of “%m%n” will be used.
name String The name of the Appender.
policy TriggeringPolicy The policy to use to determine if a rollover should occur.
strategy RolloverStrategy The strategy to use to determine the name and location of the archive file.
ignoreExceptions boolean The 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.
filePermissions String File 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.



<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logsproperty>
        <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就类似于一个整数计数器,受到控制,当文件个数达到5个的时候会循环覆盖前面已归档的1-5个文件。若不设置该参数,默认为7
    Log4j2的RollingFileAppender详解_第1张图片

DefaultRolloverStrategy Parameters

Parameter Name Type Description
fileIndex String max: 文件上到下为时间升序
min:文件上到下为时间降序
nomax:文件不覆盖,时间升序依次生成

参考此翻译 https://blog.csdn.net/yangb0803/article/details/111319935
min integer The minimum value of the counter. The default value is 1.
max integer The maximum value of the counter. Once this values is reached older archives will be deleted on subsequent rollovers. The default value is 7.
compressionLevel integer Sets the compression level, 0-9, where 0 = none, 1 = best speed, through 9 = best compression. Only implemented for ZIP files.
tempCompressedFilePattern String The 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 Name Type Description
interval
间隔
integer How 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
调整
boolean Indicates 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
最大随机延迟
integer Indicates 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:


<configuration status="info" monitorInterval="10">

    <properties>
        <property name="LOG_HOME">./applog/logsproperty>
        <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:验证小时场景

如上modulate="true"设置后,假如10点的日志开始重启服务,则从11点触发一次rollover操作,生成2020-09-09-10.log.gz对该日志进行压缩重命名并归档,并生成新的文件app.log进行日志写入;然后,每间隔6小时,则下一次是17点触发一次,生成2020-09-09-17.log.gz对该日志进行压缩重命名并归档,并生成新的文件app.log进行日志写入。






<Configuration status="warn" name="MyApp" packages="">
    
    <Appenders>
        <RollingFile name="RollingFile"
                     fileName="logs/app.log"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%nPattern>
            PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
            Policies>
        RollingFile>
    Appenders>
    
    <Loggers>
        <Root level="error">
            <AppenderRef ref="RollingFile"/>
        Root>
    Loggers>
Configuration>

上述模板中,日志先写入logs/app.log中,每当文件的时间间隔到达6小时(由%d{yyyy-MM-dd-HH}决定,也可以设置成%d{yyyy-MM-dd-HH-mm},则间隔为分钟级别),触发rollover操作。
  如上modulate="true"设置后,假如10点的日志开始重启服务,则从11点触发一次rollover操作,生成2020-09-09-10.log.gz对该日志进行压缩重命名并归档,并生成新的文件app.log进行日志写入;然后,每间隔6小时,则下一次是17点触发一次,生成2020-09-09-17.log.gz对该日志进行压缩重命名并归档,并生成新的文件app.log进行日志写入。


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

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


<Configuration status="warn" name="MyApp" packages="">
    <Appenders>
        <RollingFile name="RollingFile"
                     fileName="logs/app.log"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%nPattern>
            PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            Policies>
        RollingFile>
    Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="RollingFile"/>
        Root>
    Loggers>
Configuration>

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

你可能感兴趣的:(日志,log4j,java,开发语言)