1. RollingFileAppender解释
下面是一个使用RollingFileAppender的示例配置,该配置同时具有基于时间和大小的触发策略,将在同一天(1-100)创建最多100个存档,这些存档基于当前年份和月份存储在目录中,并将使用gzip压缩每个存档,并且将每小时滚动一次。在每次滚动更新过程中,此配置将删除与“*/app-*.log.gz”匹配且已存在30天或更久的文件,但保留最新的100 GB或最新的10个文件(以先到者为准)
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Properties>
<Property name="baseDir">logs</Property>
</Properties>
<Appenders>
<RollingFile name="RollingFile" fileName="${baseDir}/app.log"
filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
<DefaultRolloverStrategy max="100">
<!--
Nested conditions: the inner condition is only evaluated on files
for which the outer conditions are true.
-->
<Delete basePath="${baseDir}" maxDepth="2">
<IfFileName glob="*/app-*.log.gz">
<IfLastModified age="30d">
<IfAny>
<IfAccumulatedFileSize exceeds="100 GB" />
<IfAccumulatedFileCount exceeds="10" />
</IfAny>
</IfLastModified>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="RollingFile"/>
</Root>
</Loggers>
</Configuration>
2. RollingRandomAccessFileAppender 解释
RollingrandoMacAccessFileAppender与标准的RollingFileAppender类似,只是它始终处于缓冲状态(无法关闭),并且在内部使用ByteBuffer+RandomAccessFile而不是BufferedOutputStream。在我们的测量中,我们看到与使用“bufferedIO=true”的RollingFileAppender相比,性能提高了20-200%。RollingRandomAccessFileAppender将写入fileName参数中指定的文件,并根据TriggeringPolicy和RolloverPolicy将文件滚动。与RollingFileAppender类似,rollingrandomacessfileappender使用rollingrandomacessfilemanager来实际执行文件I/O和执行滚动。虽然来自不同配置的RollingRandomAccessFileAppender无法共享,但如果管理器是可访问的,则RollingRandomAccessFileManagers可以是。例如,如果Log4j位于它们共同的类加载器中,则servlet容器中的两个web应用程序可以有自己的配置并安全地写入同一文件。
RollingRandomAccessFileAppender需要触发策略和RolloverStrategy。触发策略确定是否应执行展期,而展期策略定义应如何进行展期。如果未配置RolloverStrategy,rollingrandomacessfileappender将使用DefaultRolloverStrategy。由于log4j-2.5,可以在DefaultRolloverStrategy中配置一个自定义删除操作,以便在rollover时运行。
RollingRandomAccessFileAppender不支持文件锁定。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<RollingRandomAccessFile name="RollingRandomAccessFile" 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%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="RollingRandomAccessFile"/>
</Root>
</Loggers>
</Configuration>
参考文档
1. https://logging.apache.org/log4j/2.x/manual/appenders.html