-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathlogsController.js
More file actions
96 lines (82 loc) · 2.52 KB
/
logsController.js
File metadata and controls
96 lines (82 loc) · 2.52 KB
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
/**
* 日志管理控制器
* 提供日志读取
*/
import fs from '../../utils/fsWrapper.js';
import path from 'path';
// 读取日志
export async function getLogs(req, reply) {
try {
const lines = parseInt(req.query.lines) || 50;
const logDir = path.join(process.cwd(), 'logs');
if (!await fs.pathExists(logDir)) {
return reply.send({
file: null,
content: '日志目录不存在'
});
}
const files = await fs.readdir(logDir);
const logFiles = files
.filter(f => f.endsWith('.log.txt'))
.sort()
.reverse();
if (logFiles.length === 0) {
return reply.send({
file: null,
content: '没有日志文件'
});
}
const latestLog = path.join(logDir, logFiles[0]);
const content = await fs.readFile(latestLog, 'utf-8');
const allLines = content.trim().split('\n');
const lastLines = allLines.slice(-lines);
return reply.send({
file: logFiles[0],
content: lastLines.join('\n')
});
} catch (e) {
reply.code(500).send({
error: e.message
});
}
}
async function streamLogs(socket, lines) {
try {
const logDir = path.join(process.cwd(), 'logs');
const files = await fs.readdir(logDir);
const logFiles = files
.filter(f => f.endsWith('.log.txt'))
.sort()
.reverse();
if (logFiles.length === 0) {
socket.send(JSON.stringify({
type: 'error',
message: '没有日志文件'
}));
return;
}
const latestLog = path.join(logDir, logFiles[0]);
const content = await fs.readFile(latestLog, 'utf-8');
const allLines = content.trim().split('\n');
const lastLines = allLines.slice(-lines);
// 发送现有日志
for (const line of lastLines) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: 'log',
timestamp: Date.now(),
content: line
}));
}
}
socket.send(JSON.stringify({
type: 'end',
message: `已读取 ${lastLines.length} 行日志`
}));
} catch (e) {
socket.send(JSON.stringify({
type: 'error',
message: e.message
}));
}
}