Spring 启动 - 未写入日志文件(logging.file 未得到遵守)

Spring Boot - no log file written (logging.file is not respected)

我使用 Spring Boot 并希望它将日志输出写入文件。

根据文档,这只需设置

logging.file=filename.log

虽然控制台输出工作正常,但未创建 filename.log。另外,如果我手动创建文件,则不会写入任何内容。我想念什么?

如果您使用的是 Maven,请添加依赖项:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.6</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>

现在您必须指定一个名为 'log4j.properties' 的文件,您必须将其放在特定目录中:' src/main/resources/log4j.properties '

例如,文件应该是这样的:

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=TRACE

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# log4j.appender.springlog.Threshold=INFO
log4j.appender.springlog.layout=org.apache.log4j.PatternLayout
log4j.appender.springlog.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:/example/filename.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

现在导入这些:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

像这样声明一个记录器变量:

final static Logger logger = Logger.getLogger(TheClassYourIn.class);

并像这样在 class 中使用它:

logger.info("Well hello world then ");

这种方式适合我。希望这个回答对您有所帮助。祝你好运!

PS:log4j.appender.file.File='directory' 是指定日志存储位置的方式。如果您不指定目录而只是将其保留为 filename.log,此文件将自动创建在项目目录中。

我不知道这是否对你有帮助,但我也在我的 Spring-Boot 项目中使用 Logback,结构如下

文件: logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="logback.xsd">

    <property resource="\application.properties"/>

    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${app.logPathPrefix}/myproject.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${app.logPathPrefix}/myproject.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%thread] [%logger:%line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%thread] [%logger:%line] %msg%n
            </pattern>
        </encoder>
    </appender>


    <logger name="org.springframework" level="INFO" />
    <logger name="com.mycompany" level="INFO" />
    <logger name="org.hibernate" level="DEBUG" />


    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

文件: application.properties

app.logPathPrefix=/var/log/myproject

以下是我如何设法将输出写入本地文件。 要禁用控制台日志记录并将输出仅写入文件,您需要自定义 logback-spring.xml ( 称其为 logback-spring.xml 所以您将利用 Boot) 提供的模板功能(日期格式等),导入 file-appender.xml 而不是控制台-appender.xml。为了实现这一点,您必须将下面的代码粘贴到您的 logback-spring.xml 文件中。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration> 

您还需要在 application.properties 中添加以下内容:

logging.file=myapplication.log

注意这个日志文件myapplication.log会被springboot生成。

这是我的应用程序结构树的样子:

如果你想玩得更开心,你可以像这样在你的 Maven 依赖项中找到 base.xml:

我找到了解决办法。我对它不是很满意,因为它仍然没有回答我最初的问题,为什么 logging.file 属性 不被尊重。

我从 Georges 的 in the same directory where application.properties resides. According to the documentation Spring 创建了 logback-spring.xml Boot 将从那里拾取它。显然,这不会发生在我的情况下。

我需要另外添加 logging.config=classpath:logback-spring.xml 才能被 Spring 拾取。我的 application.properties 的相关部分现在是

logging.config=classpath:logback-spring.xml
logging.file=logs/logfile.log

(我手动创建了 logs 目录。)

我遇到了同样的问题。这很可能是由于文件系统上的文件权限。我有 root 拥有的应用程序文件夹,但进程所有者拥有 ./logs。因此,以下内容无效:

logging.file=my.log

但这确实发生了

logging.file=/opt/myapp/logs/my.log

我刚刚使用了 Spring-boot 提供的日志记录机制。我在下面的 'logback.xml' 文件中写道:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file- appender.xml" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>

我将 application.properties 和 logback.xml 文件放在同一个包 'src/main/resources' 下。 在 application.properties 文件中刚刚添加了一个参数:

logging.file = xyz.log

它对我来说非常好。

在我的例子中,我错误地在我的一个子模块中添加了一个文件 "logback.xml",这导致了这个问题,删除它,一切都会好起来的。

如果你在 Spring 启动然后你可以直接 在 application.properties 文件中添加以下属性来设置日志记录级别, 自定义日志记录模式并将日志存储在外部文件中。

这些是不同的日志记录级别及其从最小值 << 最大值的顺序。

OFF << FATAL << ERROR << WARN << INFO << DEBUG << TRACE << ALL

# To set logs level as per your need.
logging.level.org.springframework = debug
logging.level.tech.hardik = trace

# To store logs to external file
# Here use strictly forward "/" slash for both Windows, Linux or any other os, otherwise, your logs it won't work.      
logging.file=D:/spring_app_log_file.log

# To customize logging pattern.
logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"

请通过这个link来更形象地自定义您的日志。

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

抱歉回复晚了。 spring 的记录器似乎从它自己的 class 路径读取 属性。Due to precedence, 它不尊重所提供的属性。

一些绕过的技巧:

  1. 在主 class 中使用 springApplication.setDefaultProperties(properties); 像这样设置 属性 变量
public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(MainClass.class);
        Properties properties = new Properties();
        properties.put("logging.file", logDirectory);
        springApplication.setDefaultProperties(properties);
        springApplication.run(args);
    }
  1. 将 属性 作为 JVM 参数传递 -Dlogging.file=/location/output.log

以上两个都不是最好的,因为为了定义其他日志记录属性,它们也应该遵循相同的方式。

解决方案

定义一个 属性 文件并将所有日志记录配置放入其中,并在 -Dspring.config.location 中指定该文件。这是 and 的推导。检查一下以了解我尝试过的其他解决方案及其挑战。

我也遇到了同样的问题,因为我只是将路径复制为 windows(在路径中使用“\”)提供。

只需将路径中的反斜杠(“\”)更改为正斜杠(“/”)即可修复。

注意:路径中应严格使用正斜杠(“/”),OS 不是约束条件。

ex:- logging.file.name=D:/Logs/server.log

我 运行 我的 spring 使用命令行参数的引导服务工作正常。所有 spring 引导控制台日志都写入该文件。我的 application.properties 文件中没有配置任何日志记录。 Spring 引导版本:2.0.5.RELEASE

在windows中:

java -jar target\microservice-0.0.1.jar --logging.file=C:\logs\microservice.log

在Linux

java -jar target\microservice-0.0.1.jar --logging.file=\var\log\microservice.log

在我的例子中,我粘贴了一些典型的配置,但很可能以某种方式弄乱了我的日志记录模式 (logging.pattern.file)

将其注释掉解决了我自己的问题(文件已创建,但其中没有写入任何内容,即使有控制台输出并且根日志记录级别设置为 DEBUG)- 否则没有给出错误。

[edit] 在其他情况下(我似乎总是遇到这个问题),我引用了一个从 Web 应用程序 (WAR) 中剥离的 类 的 JAR 文件,其中包含一个logback.xml,更不用说 AppInitializer - 我怀疑 AppInitializer 不会有问题,因为它有一个完全不同的包名,不应该被 Spring 自动配置扫描..但是 logback.xml 被检测到,我猜,在类路径中,并且完全搞砸了一切。我知道引用 WAR 是一种 hack,但我希望有一个快速修复 - 修复它,破坏其他东西。 相关。

在我的例子中,我在应用程序 属性 文件中使用了下面的内容。

logging.file

相反,我需要使用下面的:

logging.file.name

从那以后,我就可以把日志放到定向路径文件中了。

使用logging.file.name代替logging.file

spring-boot-parent(from version 2.2.0) 的更高版本中,属性 logging.file 已弃用。

查看Springboot父版本

如果是 2.3.x+ 那么 属性 应该是 logging.file.name=yourapplog.log

我在 windows 操作系统中也遇到了同样的问题。我刚刚将 -> logging.file 更改为 logging.file.name=D:/customer_projects/flight_reservation_system/logs/reservation.log

注意:Spring-我使用的启动版本是2.4.1

在 windows 操作系统中,当您从文件资源管理器复制文件路径时,您将获得类似 D:\customer_projects\flight_reservation_system\logs\flight_reservation.log

的文件路径

以上文件路径无效。所以您需要更改文件路径,例如 D:/customer_projects/flight_reservation_system/logs/reservation.log 然后它会在我们指定的路径中创建一个日志文件。谢谢。

如果你想将日志文件放在特定的目录中,比如 D 驱动器,那么可以在 spring 启动项目中进行以下更改

1.Create logback-spring.xml 配置文件并注明要创建日志的包名称

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    
        <logger name="com.example.demo" 
        level="DEBUG" >
           
        </logger>
</configuration>

2.Also 在 application.properties 文件中添加以下内容

logging.config=classpath:logback-spring.xml
logging.file.name=F:/Springbootlogs/filename.log

注意:提到的更改是针对版本 2.4.3

Spring 引导:版本 2.4.3

应在 application.properties 文件中使用其中之一:logging.file.namelogging.file.path

例如:

logging.file.name=logs/myapp.log
logging.file.path=logs

您不必创建 logs 目录。它将在 class 路径中自动创建。

要查看其他已弃用的属性,请阅读此 class 文件 ~/.m2/repository/org/springframework/boot/spring-boot/2.4.3/spring-boot-2.4.3.jar!/org/springframework/boot/logging/LoggingSystemProperties.class

对于 Spring Boot 2.4.2,以下 Application.yml 配置有效:

logging:
    file:
        name: logpath