1. 按記錄層級區分檔案輸出
有些人習慣按日誌資訊層級輸出到不同名稱的檔案中,如info.log,error.log,warn.log等,在log4j2中可通過配置Filters來實現。
假定需求是把INFO及以下層級的資訊輸出到info.log,WARN和ERROR層級的資訊輸出到error.log,FATAL層級輸出到fatal.log,設定檔如下:
[java] view plain copy print ? <Configuration status="WARN" monitorInterval="300"> <properties> <property name="LOG_HOME">D:/logs</property> </properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> <RollingRandomAccessFile name="InfoFile" fileName="${LOG_HOME}/info.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <Filters> <ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL" /> <ThresholdFilter level="trace" 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> <RollingRandomAccessFile name="ErrorFile" fileName="${LOG_HOME}/error.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"> <Filters> <ThresholdFilter level="fatal" 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> <RollingRandomAccessFile name="FatalFile" fileName="${LOG_HOME}/fatal.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/fatal-%d{yyyy-MM-dd}-%i.log"> <Filters> <ThresholdFilter level="fatal" onMatch="ACCEPT" onMismatch="DENY" />