log4j2日志xml配置——不同级别的日志分别记录在不同的文件

时间:2022-05-27 21:52:12
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<Configuration status="WARN" monitorInterval="500">
<!--定义日志储存文件目录-->
<properties>
<property name="LOG_HOME">logs</property>
</properties>
<Appenders>
<!--控制台输出所有日志-->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<!--Info级别日志输出-->
<RollingRandomAccessFile name="InfoFile"
fileName
="${LOG_HOME}/info/info.log"
filePattern
="${LOG_HOME}/info-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
</Filters>
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>
<!--warn级别日志输出-->
<RollingRandomAccessFile name="WarnFile"
fileName
="${LOG_HOME}/warn/warn.log"
filePattern
="${LOG_HOME}/warn-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>

<!--Error级别日志输出-->
<RollingRandomAccessFile name="ErrorFile"
fileName
="${LOG_HOME}/error/error.log"
filePattern
="${LOG_HOME}/error-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" />
</Filters>
<PatternLayout pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>
</Appenders>

<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<Loggers>
<!--过滤掉spring的一些无用的DEBUG信息-->
<logger name="org.springframework" level="INFO"></logger>
<Root level="Debug">
<AppenderRef ref="Console" />
<AppenderRef ref="InfoFile" />
<AppenderRef ref="WarnFile" />
<AppenderRef ref="ErrorFile" />
</Root>
</Loggers>

</Configuration>

 PS:以上是xml配置全文件。可完全复制粘贴替换xml内容。