前一篇文章介绍了log4j2 扩展日志级别,支持将系统日志与业务处理日志拆分,现在介绍一下通过日志级别将系统日志与业务日志分类,要达到这个目的很容易,只需要配置一下log4j的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <Properties> <property name="log_pattern">%m%n</property> <property name="basePath">/data/logs/</property> <property name="system-msg">${basePath}/system.log</property> <property name="business-a-msg">${basePath}/service_a.log</property> <property name="business-b-msg">${basePath}/service_b.log</property> <property name="rollingfile_system-msg">${basePath}/system%d{yyyy-MM-dd}.log</property> <property name="rollingfile_business-a-msg">${basePath}/service_a%d{yyyy-MM-dd}.log</property> <property name="rollingfile_business-b-msg">${basePath}/service_b%d{yyyy-MM-dd}.log</property> </Properties> <appenders> <Console name="console" target="SYSTEM_OUT"> <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="ACCEPT" /> <PatternLayout pattern="${log_pattern}" /> </Console> <RollingFile name="appender_system-msg" filename="${system-msg}" filePattern="${rollingfile_system-msg}" append="true"> <Filters> <ThresholdFilter level="business" onMatch="NEUTRAL" onMismatch="ACCEPT"/> </Filters> <PatternLayout> <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %class{36} %L %M - %msg%xEx%n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> </Policies> </RollingFile> <RollingFile name="appender_business-a-msg" filename="${business-a-msg}" filePattern="${rollingfile_business-a-msg}" append="true"> <ThresholdFilter level="business" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout> <Pattern>${log_pattern}</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> </Policies> </RollingFile> <RollingFile name="appender_business-b-msg" filename="${business-b-msg}" filePattern="${rollingfile_business-b-msg}" append="true"> <ThresholdFilter level="business" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout> <Pattern>${log_pattern}</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> </Policies> </RollingFile> </appenders> <loggers> <AsyncLogger name="com.jessezeng" level="info" additivity="true" includeLocation="true"> <AppenderRef ref="appender_system-msg" /> </AsyncLogger> <AsyncLogger name="com.jessezeng.service.a.ServiceAImpl" level="info" additivity="true" includeLocation="true"> <AppenderRef ref="appender_business-a-msg" /> </AsyncLogger> <AsyncLogger name="com.jessezeng.service.b.ServiceBImpl" level="info" additivity="true" includeLocation="true"> <AppenderRef ref="appender_business-b-msg" /> </AsyncLogger> <Root level="info"> <AppenderRef ref="console" /> </Root> </loggers> </configuration>
通过上面的配置就可以达到我们想要的目的,主要用到了log4j2日志级别过滤,可参考另一篇文章 log4j2按日志级别输出到指定文件。