将日期时间添加到日志文件名

问题描述 投票:0回答:2

我有一些日志要写入spring-boot微服务中的文件。

在我的“ application.yml”中,下面一行工作正常。但我也想在文件名中添加日期和时间。我该怎么办?

logging:
  file: logs/${spring.application.name}.log

理想情况下,我希望文件名是这样的:

logs/spring-boot-application_YYYY_MM_DD_HH_MM
spring-boot logging slf4j
2个回答
0
投票

这里已经回答了类似的问题:How to include date in log file's name with Spring Boot / slf4j?

基本上,如果要对日志记录设置进行更多控制,则应在src / main / resources下拥有自己的logback.xml并配置类似于以下内容的命名格式:

<FileNamePattern>LogFile.%d{yyyy-MM-dd}.log</FileNamePattern>

0
投票

如果使用spring-boot,则可以在application.ymlapplication.properties中轻松指定它,并配置logback xml以将Rolling File Appender启用为:

spring:
logging:
  file: logs/dev_app.log
  pattern:
    console: "%d %-5level %logger : %msg%n"
    file: "%d %-5level [%thread] %logger : %msg%n"
  level:
    org.springframework.web: DEBUG
    guru.springframework.controllers: DEBUG
    org.hibernate: DEBUG

并在以下位置为文件指定基于时间的滚动策略:>

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <include resource="org/springframework/boot/logging/logback/base.xml"/>

  <appender name="ROLLIN" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_FILE}</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

        <!-- daily rollover -->
        <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.log</fileNamePattern>

    </rollingPolicy>
  </appender>

  <root level="INFO">
    <appender-ref ref="ROLLIN" />
  </root>

  <logger name="org.springframework.web" level="INFO"/>
</configuration>

DocOfficial Spring Doc

© www.soinside.com 2019 - 2024. All rights reserved.