Log4j2 日志按级别输出到不同文件
在生产环境中,可以按日志信息级别,输出到不同的文件中,如生成 info.log,warn.log,error.log 等;
这样的功能可以通过在 log42.xml 中配置Filter来实现;
一个示例的实现如下:
log4j2.xml
1
<Configuration status="WARN" monitorInterval="500">
2
3
<!--定义日志储存文件目录-->
4
<properties>
5
<property name="LOG_HOME">user/logs</property>
6
</properties>
7
8
<Appenders>
9
<!--控制台输出所有日志-->
10
<Console name="Console" target="SYSTEM_OUT">
11
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
12
</Console>
13
14
<!--Info级别日志输出-->
15
<RollingRandomAccessFile name="InfoFile"
16
fileName="${LOG_HOME}/info/info.log"
17
filePattern="${LOG_HOME}/info-%d{yyyy-MM-dd}-%i.log">
18
<Filters>
19
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL" />
20
<ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY" />
21
</Filters>
22
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
23
<Policies>
24
<TimeBasedTriggeringPolicy />
25
<SizeBasedTriggeringPolicy size="10 MB" />
26
</Policies>
27
<DefaultRolloverStrategy max="20" />
28
</RollingRandomAccessFile>
29
30
<!--Error级别日志输出-->
31
<RollingRandomAccessFile name="ErrorFile"
32
fileName="${LOG_HOME}/error/error.log"
33
filePattern="${LOG_HOME}/error-%d{yyyy-MM-dd}-%i.log">
34
<Filters>
35
<ThresholdFilter level="fatal" onMatch="DENY" onMismatch="NEUTRAL" />
36
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY" />
37
</Filters>
38
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
39
<Policies>
40
<TimeBasedTriggeringPolicy />
41
<SizeBasedTriggeringPolicy size="10 MB" />
42
</Policies>
43
<DefaultRolloverStrategy max="20" />
44
</RollingRandomAccessFile>
45
46
<!--Fatal级别日志输出-->
47
<RollingRandomAccessFile name="FatalFile"
48
fileName="${LOG_HOME}/fatal/fatal.log"
49
filePattern="${LOG_HOME}/fatal-%d{yyyy-MM-dd}-%i.log">
50
<Filters>
51
<ThresholdFilter level="fatal" onMatch="ACCEPT" onMismatch="DENY" />
52
</Filters>
53
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
54
<Policies>
55
<TimeBasedTriggeringPolicy />
56
<SizeBasedTriggeringPolicy size="10 MB" />
57
</Policies>
58
<DefaultRolloverStrategy max="20" />
59
</RollingRandomAccessFile>
60
</Appenders>
61
62
<Loggers>
63
<Root level="Debug">
64
<AppenderRef ref="Console" />
65
<AppenderRef ref="InfoFile" />
66
<AppenderRef ref="ErrorFile" />
67
<AppenderRef ref="FatalFile" />
68
</Root>
69
</Loggers>
70
</Configuration>