1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
| package com.touchsmail.controller.tools.log;
import com.touchsmail.util.StringUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.time.*; import java.time.format.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.PreDestroy; import javax.annotation.Resource;
@RestController @RequestMapping("/service/logs") public class SystemLogController {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final ExecutorService executor = Executors.newCachedThreadPool();
@Resource private LogReaderProperties properties;
private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); headers.set(HttpHeaders.CONTENT_ENCODING, "UTF-8"); headers.set(HttpHeaders.CONTENT_TYPE, "text/plain;charset=UTF-8"); return headers; }
private void checkEnabled() { if (!properties.isEnabled()) { throw new IllegalStateException("log not open!"); } }
private void checkFileExists() { if (StringUtils.isBlank(properties.getFilePath()) || !Files.exists(Paths.get(properties.getFilePath()))) { throw new IllegalStateException("log file does not exist!"); } }
@GetMapping("/") public ResponseEntity<String> explain() { checkEnabled(); checkFileExists(); final String content = "// 读取全部日志\n" + "GET http://localhost:6001/service/logs/all\n" + "\n" + "// 读取最新10条日志\n" + "GET http://localhost:6001/service/logs/latest?lines=10\n" + "\n" + "// 读取指定时间范围的日志\n" + "GET http://localhost:6001/service/logs/time?startTime=2024-12-01 00:00:00&endTime=2024-12-31 00:00:00\n" + "\n" + "// 流式读取日志\n" + "GET http://localhost:6001/service/logs/stream?bufferSize=100"+ "// 流式追踪最新日志\n" + "GET http://localhost:6001/service/logs/realtime"; return new ResponseEntity<>(content, getHeaders(), HttpStatus.OK); }
@GetMapping("/all") public ResponseEntity<String> readAllLogs() { checkEnabled(); checkFileExists(); try { String content = new String(Files.readAllBytes(Paths.get(properties.getFilePath())), StandardCharsets.UTF_8); return new ResponseEntity<>(content, getHeaders(), HttpStatus.OK); } catch (IOException e) { return new ResponseEntity<>("读取日志文件失败: " + e.getMessage(), getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
@GetMapping("/latest") public ResponseEntity<String> readLatestLogs(@RequestParam(defaultValue = "10") int lines) { try { checkEnabled(); checkFileExists(); List<String> allLines = Files.readAllLines(Paths.get(properties.getFilePath()), StandardCharsets.UTF_8); int startIndex = Math.max(0, allLines.size() - lines); List<String> latestLines = allLines.subList(startIndex, allLines.size());
StringBuilder result = new StringBuilder(); for (String line : latestLines) { result.append(line).append("\n"); }
return new ResponseEntity<>(result.toString(), getHeaders(), HttpStatus.OK); } catch (IOException e) { return new ResponseEntity<>("读取日志文件失败: " + e.getMessage(), getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
@GetMapping("/time") public ResponseEntity<String> readLogsByTimeRange( @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) { try { checkEnabled(); checkFileExists(); List<String> allLines = Files.readAllLines(Paths.get(properties.getFilePath()), StandardCharsets.UTF_8); StringBuilder result = new StringBuilder();
for (String line : allLines) { try { String timeStr = line.substring(0, 19); LocalDateTime logTime = LocalDateTime.parse(timeStr, DATE_FORMAT);
if ((logTime.isEqual(startTime) || logTime.isAfter(startTime)) && (logTime.isEqual(endTime) || logTime.isBefore(endTime))) { result.append(line).append("\n"); } } catch (Exception e) { continue; } }
return new ResponseEntity<>(result.toString(), getHeaders(), HttpStatus.OK); } catch (IOException e) { return new ResponseEntity<>("读取日志文件失败: " + e.getMessage(), getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
@GetMapping("/stream") public ResponseEntity<String> streamLog(@RequestParam(defaultValue = "100") int maxLines) { try { checkEnabled(); checkFileExists(); List<String> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(properties.getFilePath()), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); if (lines.size() > maxLines) { lines.remove(0); } } }
StringBuilder result = new StringBuilder(); for (String line : lines) { result.append(line).append("\n"); }
return new ResponseEntity<>(result.toString(), getHeaders(), HttpStatus.OK); } catch (IOException e) { return new ResponseEntity<>("读取日志文件失败: " + e.getMessage(), getHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
@GetMapping("/realtime") public SseEmitter streamLogRealtime(@RequestParam(defaultValue = "0") int initialLines, @RequestParam(required = false) String filePath) {
SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); Path logFilePath = (filePath != null && !filePath.isEmpty()) ? Paths.get(filePath) : Paths.get(properties.getFilePath());
if (!Files.exists(logFilePath)) { throw new RuntimeException("Log file not found: " + filePath); }
executor.execute(() -> { try { WatchService watchService = FileSystems.getDefault().newWatchService(); logFilePath.getParent().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
AtomicLong filePointer = new AtomicLong(Files.size(logFilePath));
if (initialLines > 0) { List<String> lastLines = readLastLines(logFilePath, initialLines); for (String line : lastLines) { emitter.send(SseEmitter.event().data(line)); } }
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(() -> { try { long newSize = Files.size(logFilePath); if (newSize > filePointer.get()) { try (RandomAccessFile file = new RandomAccessFile(logFilePath.toFile(), "r"); InputStreamReader isr = new InputStreamReader(new FileInputStream(file.getFD()), StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr)) {
file.seek(filePointer.get()); String line; while ((line = reader.readLine()) != null) { emitter.send(SseEmitter.event().data(line)); } filePointer.set(file.getFilePointer()); } } } catch (IOException e) { emitter.completeWithError(e); } }, 0, 1, TimeUnit.SECONDS);
while (true) { WatchKey key = watchService.take(); boolean fileDeleted = false;
for (WatchEvent<?> event : key.pollEvents()) { Path changed = (Path) event.context(); if (changed.endsWith(logFilePath.getFileName())) { if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { fileDeleted = true; } } }
key.reset();
if (fileDeleted) { emitter.send(SseEmitter.event().data("Log file deleted. Stopping log streaming.")); emitter.complete(); scheduler.shutdown(); break; } } } catch (IOException | InterruptedException e) { emitter.completeWithError(e); } });
return emitter; }
private List<String> readLastLines(Path filePath, int lines) throws IOException { List<String> result = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { List<String> allLines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
int start = Math.max(allLines.size() - lines, 0); for (int i = start; i < allLines.size(); i++) { result.add(allLines.get(i)); } } return result; }
@PreDestroy public void shutdownExecutor() { executor.shutdown(); }
}
|