【传送门】:log4j官网配置文件详解
1. 排除 spring boot 自带的 spring-boot-starter-logging 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <!-- remove log4j --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency>
2. 添加spring-boot-log4j2 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <!--如果配置文件为yaml格式,则还需添加如下依赖--> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.9.7</version> </dependency>
3. log4j.xml配置示例
<?xml version="1.0" encoding="UTF-8"?> <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <!-- status log4j2 内部日志级别 --> <configuration status="INFO"> <!-- 全局参数 --> <Properties> <Property name="pattern">[%p] %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %l : %m%n</Property> <Property name="logHome">logs</Property> <Property name="displayName">monitor-server</Property> </Properties> <Appenders> <Console name="console" target="SYSTEM_OUT" follow="true"> <PatternLayout> <pattern>${pattern}</pattern> </PatternLayout> </Console> <!-- 文件 每次运行程序会自动清空,由append属性决定 --> <File name="error" fileName="${loghome}/${displayName}_error.log" append="false"> <!-- 指定error 级别的日志 --> <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout> <pattern>${pattern}</pattern> </PatternLayout> </File> <!-- 滚动文件 --> <RollingFile name="rollingFile" fileName="${logHome}/${displayName}.log" filePattern="${logHome}/${displayName}_%d{yyyy-MM-dd}.log"> <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout> <pattern>${pattern}</pattern> </PatternLayout> <!-- 按大小划分 --> <Policies> <SizeBasedTriggeringPolicy size="10 MB"/> </Policies> </RollingFile> </Appenders> <Loggers> <Logger name="org.springframework" level="WARN" additivity="false"> <AppenderRef ref="console"/> </Logger> <Logger name="com.skd.server" level="info" additivity="false"> <AppenderRef ref="console"></AppenderRef> <AppenderRef ref="error"></AppenderRef> <AppenderRef ref="rollingFile"></AppenderRef> </Logger> <!--日志信息输出的最低级别--> <Root level="debug"> </Root> </Loggers> </configuration>