SpringBoot 基于 SSE(Server-Send-Event)实现日志文件实时监控


一. 后端接口实现:

@GetMapping(value = "/log")
@ResponseBody
public SseEmitter realtimeLog() {
    SseEmitter emitter = new SseEmitter(0L);
    String file = "./log.log";
    Tailer tailer = new Tailer(FileUtil.newFile(file), StandardCharsets.UTF_8, line -> {
        try {
            emitter.send(line);
        } catch (IOException e) {
            log.error("SSE响应日志异常", e);
            throw new RuntimeException(e);
        }
    }, 10, DateUnit.SECOND.getMillis());
    tailer.start(true);
    emitter.onCompletion(tailer::stop);
    return emitter;
}

二. 前端实现

<!DOCTYPE html>
<html>
<head>
    <title>实时日志监控</title>
</head>
<body>
    <div id="log"></div>
    
    <script>
        const logElement = document.getElementById('log');
        const eventSource = new EventSource('/log');
        
        eventSource.onmessage = function(event) {
            logElement.innerHTML += event.data + '<br>';
        };
        
        eventSource.onerror = function(error) {
            console.error('EventSource failed:', error);
            eventSource.close();
        };
    </script>
</body>
</html>

评论已关闭