You need to enable JavaScript to run this app. Spring Boot如何通过RestController实现日志文件在线查看REST接口
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何通过RestController实现日志文件在线查看REST接口

Spring Boot 日志查看接口实现方案

1. 前置配置

先在项目配置文件中声明日志文件路径和最大读取行数限制,避免大文件读取导致服务异常:

# application.yml 示例配置
logging:
  file:
    name: ./logs/application.log # 替换为你的实际日志文件路径
# 自定义配置:单次接口返回的最大日志行数
log:
  view:
    max-lines: 2000

2. 编写日志查询Controller

直接实现倒序读取最新日志行的逻辑,响应头设置为纯文本格式,确保浏览器直接展示内容而不是触发下载:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/info/log")
public class LogViewController {

    @Value("${logging.file.name}")
    private String logFilePath;

    @Value("${log.view.max-lines:2000}")
    private Integer maxAllowLines;

    @GetMapping("/file")
    public void getLatestLog(@RequestParam(value = "lines", required = false) Integer expectLines,
                             HttpServletResponse response) throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        int readLines = expectLines == null ? maxAllowLines : Math.min(expectLines, maxAllowLines);

        File logFile = new File(logFilePath);
        if (!logFile.exists() || !logFile.isFile()) {
            response.getWriter().write("日志文件不存在");
            return;
        }
        if (logFile.length() == 0) {
            response.getWriter().write("日志文件为空");
            return;
        }

        List<String> logLines = new ArrayList<>();
        // 从文件末尾倒序读取,避免加载全量日志占用过多内存
        try (RandomAccessFile raf = new RandomAccessFile(logFile, "r")) {
            long pointer = raf.length() - 1;
            StringBuilder currentLine = new StringBuilder();
            while (pointer >= 0 && logLines.size() < readLines) {
                raf.seek(pointer);
                byte b = raf.readByte();
                if (b == '\n') {
                    if (currentLine.length() > 0) {
                        logLines.add(currentLine.reverse().toString());
                        currentLine.setLength(0);
                    }
                } else if (b != '\r') {
                    currentLine.append((char) b);
                }
                pointer--;
            }
            if (currentLine.length() > 0) {
                logLines.add(currentLine.reverse().toString());
            }
        } catch (Exception e) {
            response.getWriter().write("日志读取失败: " + e.getMessage());
            return;
        }
        // 反转列表恢复日志时间正序,最新日志显示在页面底部
        for (int i = logLines.size() - 1; i >= 0; i--) {
            response.getWriter().write(logLines.get(i));
            response.getWriter().write("\n");
        }
        response.getWriter().flush();
    }
}

3. 安全与使用说明

  • 必须给接口加访问权限控制,可通过Spring Security限定管理员角色访问,或配置网关IP白名单,禁止公网直接暴露该接口,避免日志中的敏感信息泄露
  • 生产环境建议仅在调试阶段开启该接口,问题排查完成后及时关闭
  • 支持自定义返回行数,访问格式为 http://服务地址/info/log/file?lines=3000 即可返回最新3000行日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:36:03