Log4j2 日誌分級別輸出到不同檔案
阿新 • • 發佈:2019-01-01
Log4j2 日誌按級別輸出到不同檔案
在生產環境中,可以按日誌資訊級別,輸出到不同的檔案中,如生成 info.log,warn.log,error.log 等; 這樣的功能可以通過在 log42.xml 中配置Filter來實現; 一個示例的實現如下: log4j2.xml1
<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>