折腾:
【未解决】给Spring Boot的java项目中加上输出日志到文件中
期间,去配置:
src/server/xxx/xxx/pom.xml
<properties> <java.version>1.8</java.version> <log4j2.version>2.13.0</log4j2.version> </properties> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency>
且更新了配置:
以及加上了配置文件:
src/server/xxx/xxx/src/main/resources/log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <File name="FILEOUT" fileName="xxx.log" append="false"> <PatternLayout> <Pattern>%d{yyyyMMdd HH:mm:ss} %-5p [%t] %C{2} %F%L - %m%n</Pattern> </PatternLayout> </File> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p %F:%L - %m%n"/> </Console> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="FILEOUT"/> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration>
但是代码
src/server/xxx/xxx/src/main/java/com/crifan/xxx/GreetingController.java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GreetingController { private static Logger logger = LoggerFactory.getLogger(GreetingController.class); @PostMapping(path = "/greeting", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public Greeting addMember(@RequestBody Map<String, Object> payload) { logger.info("post greeting: payload={}", payload); }
始终没能生成日志文件。
所以感觉问题转换为:
spring boot log4j2 not generate file
去试试:
<exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions>
如图:
结果:
问题依旧。
额外再加上:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
以及
src/server/xxx/xxx/src/main/resources/application.properties
logging.config=src/main/resources/log4j2.xml
结果:
可以生成log文件了:
【总结】
此处之前之所以配置好了,但是没有日志文件,主要是:
spring-boot默认用自己的log库是logback
所以此处虽然有console的log输出,但是并没有log文件生成,即log4j2的配置没生效。
想要生成日志文件,即让log4j2的配置生效,需要:
禁止掉spring-boot的log
具体配置是:
src/server/xxx/xxx/pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion>