Log4j 使用多个文件记录日志 RollingFileAppender类
您可能因为某些原因,需要将日志写入多个文件,比如当文件大小达到一定阀值时。
为了将日志写入多个文件,您需要使用org.apache.Log4j.RollingFileAppender,该类继承了FileAppender类,继承了它的所有属性。
除了上述提到的FileAppender类的属性,该类还包括如下可配置的属性:
| RollingFileAppender新增属性 | 描述 |
|---|---|
maxFileSize |
这是文件大小的关键值,大于该值时,文件会回滚。该值默认为10MB。 |
maxBackupIndex |
该值表示备份文件的个数,默认为1。 |
log4j.properties
下面是为RollingFileAppender定义的示例配置文件Log4j.properties:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27# Define the root logger with appender file
= DEBUG, FILE
# Define the file appender
=org.apache.log4j.RollingFileAppender
# Set the name of the file
=log.out
# Set the immediate flush to true (default)
=true
# Set the threshold to debug mode
=debug
# Set the append to false, should not overwrite
=true
# Set the maximum file size before rollover
=5KB
# Set the the backup index
=2
# Define the layout for file appender
=org.apache.log4j.PatternLayout
=%m%n
如果您想使用XML配置文件,可以像上一节一样生成XML配置文件,只需添加和RollingFileAppender相关的配置即可。
该示例配置文件展示了每个日志文件最大为5MB,如果超过该最大值,则会生成一个新的日志文件。由于maxBackupIndex的值为2,当第二个文件的大小超过最大值时,会擦去第一个日志文件的内容,所有的日志都回滚至第一个日志文件。