我有一个Spring Boot应用程序,它按照https://www.baeldung.com/spring-boot-logging的教程尝试使用slf4j,但是日志仅在控制台端打印。在给定目录/var/logs
中没有创建日志文件。
log4j2-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%style{%d{ISO8601}}{black} %highlight{%-5level }[%style{%t}{bright,blue}] %style{%C{1.}}{bright,yellow}: %msg%n%throwable" />
</Console>
<RollingFile name="RollingFile"
fileName="/var/logs/spring-boot-logger-log4j2.log"
filePattern="/var/logs/$${date:yyyy-MM}/spring-boot-logger-log4j2-%d{-dd-MMMM-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<!-- rollover on startup, daily and when the file reaches
10 MegaBytes -->
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy
size="10 MB" />
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!-- LOG everything at INFO level -->
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
<Logger name="com.buraktas">
<AppenderRef ref="LogFile"/>
<AppenderRef ref="Console"/>
</Logger>
</Loggers>
</Configuration>
Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
答案 0 :(得分:1)
您可以在application.properties
文件中定义日志路径,例如,检查以下链接:
logging.level.com.example.springscheduler = debug
logging.level.org.springframework.web = WARN
logging.file.name =log/loggingdemocontroller.log
https://springbootmvc.blogspot.com/2020/06/spring-boot-logging-using-orgslf4jlogger.html
答案 1 :(得分:0)
我发现了我有spring-boot-starter
和spring-boot-starter-web
依赖性的问题。我仅从其中之一排除了spring-boot-starter-logging
依赖性,这迫使spring使用logback logger。而且由于logback logger不会选择log4j2.xml
进行配置,因此不会创建任何文件。所以pom.xml文件就是这样;
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
我还需要从spring-boot-starter-logging
依赖项中排除spring-boot-starter
。好吧,毕竟我有了spring-boot-starter-web
,所以我只是删除了spring-boot-starter
不需要的软件包。