You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Spring Boot Actuator按日期获取日志?

能否通过Spring Boot Actuator实现按日期参数获取日志?

原生Spring Boot Actuator的/actuator/logfile端点不支持直接通过URL参数指定日期获取历史日志,但可以通过扩展该端点或自定义新端点的方式实现需求,核心是基于按日期滚动生成的日志文件,通过参数匹配对应文件并返回内容。


前提准备:配置日志按日期滚动

首先需要确保你的日志框架(如Logback)配置了按日期滚动的策略,生成带日期后缀的日志文件(例如app-2024-05-20.log)。以Logback为例,配置示例如下:

<!-- logback.xml 核心配置 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/app.log</file> <!-- 当前日志文件 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>logs/app-%d{yyyy-MM-dd}.log</fileNamePattern> <!-- 历史日志命名规则 -->
        <maxHistory>30</maxHistory> <!-- 保留30天日志 -->
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

方案一:扩展原生LogFileWebEndpoint

重写原生端点的逻辑,添加日期参数支持,无参数时保留原功能返回当前日志。

1. 自定义端点类

import org.springframework.boot.actuate.logging.LogFileWebEndpoint;
import org.springframework.boot.actuate.logging.LogFileWebEndpointProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

@RestController
public class CustomLogFileEndpoint extends LogFileWebEndpoint {

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private final String logFilePrefix;

    public CustomLogFileEndpoint(LogFileWebEndpointProperties properties) {
        super(properties);
        // 提取日志文件前缀(去掉.log后缀)
        String fullPath = properties.getExternalFile();
        this.logFilePrefix = fullPath.substring(0, fullPath.lastIndexOf("."));
    }

    @GetMapping("/actuator/logfile")
    public ResponseEntity<Resource> getLogFile(@RequestParam Optional<String> date) {
        // 无日期参数时返回当前日志
        if (date.isEmpty()) {
            return super.logFile();
        }

        try {
            // 解析日期参数,拼接历史日志文件名
            LocalDate targetDate = LocalDate.parse(date.get(), DATE_FORMAT);
            String targetLogFile = logFilePrefix + "-" + targetDate.format(DATE_FORMAT) + ".log";
            File logFile = new File(targetLogFile);

            if (!logFile.exists()) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok(new FileSystemResource(logFile));
        } catch (Exception e) {
            // 日期格式错误返回400
            return ResponseEntity.badRequest().build();
        }
    }
}

2. 配置application.yml

指定外部日志文件路径,并暴露logfile端点:

management:
  endpoints:
    web:
      exposure:
        include: logfile
  endpoint:
    logfile:
      external-file: logs/app.log # 对应logback配置的当前日志文件路径

使用方式

  • 获取当前日志:GET /actuator/logfile
  • 获取指定日期日志:GET /actuator/logfile?date=2024-05-20

方案二:自定义全新端点

如果不想修改原生端点,可以创建一个独立的/actuator/logs端点,专门处理按日期查询日志的需求。

1. 自定义端点类

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
@Endpoint(id = "logs")
public class DateBasedLogEndpoint {

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private final String logFilePrefix = "logs/app"; // 对应logback配置的日志前缀

    @ReadOperation
    public ResponseEntity<Resource> getLogByDate(@Selector String date) {
        try {
            LocalDate targetDate = LocalDate.parse(date, DATE_FORMAT);
            String targetLogFile = logFilePrefix + "-" + targetDate.format(DATE_FORMAT) + ".log";
            File logFile = new File(targetLogFile);

            if (!logFile.exists()) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok(new FileSystemResource(logFile));
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}

2. 配置application.yml

暴露自定义的logs端点:

management:
  endpoints:
    web:
      exposure:
        include: logs

使用方式

获取指定日期日志:GET /actuator/logs/2024-05-20


注意事项

  • 确保日志文件的路径、命名规则与代码中的拼接逻辑完全匹配,否则会返回404
  • 需处理日期格式错误、文件不存在等异常场景,返回合适的HTTP状态码
  • 建议添加权限控制(如Spring Security),避免未授权用户访问敏感日志内容
  • 若使用Log4j2等其他日志框架,只需调整对应框架的滚动策略配置即可

内容的提问来源于stack exchange,提问作者dmance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:25:19