项目中用到的一个log4j2.xml的配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!--设置log4j2的自身log级别为warn--> <configuration status="warn"> <appenders> <console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> </console> <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/scpip-alamr-api/info.log" filePattern="${sys:user.home}/logs/scpip-alamr-api/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <Filters> <ThresholdFilter level="INFO"/> <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/> </Filters> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/scpip-alamr-api/warn.log" filePattern="${sys:user.home}/logs/scpip-alamr-api/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <Filters> <ThresholdFilter level="WARN"/> <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/> </Filters> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/scpip-alamr-api/error.log" filePattern="${sys:user.home}/logs/scpip-alamr-api/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="ERROR"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> </appenders> <loggers> <!--过滤掉spring和hibernate的一些无用的debug信息--> <logger name="org.springframework" level="INFO"> </logger> <logger name="org.hibernate" level="INFO"> </logger> <root level="all"> <appender-ref ref="Console"/> <appender-ref ref="RollingFileInfo"/> <appender-ref ref="RollingFileWarn"/> <appender-ref ref="RollingFileError"/> </root> </loggers> </configuration>
涉及到的pom.xml中的配置如下
<!--log4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.19</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jcl</artifactId> <version>2.5</version> </dependency>
在类中如下写:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; private final Logger logger = LoggerFactory.getLogger(this.getClass());