-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (85 loc) · 2.91 KB
/
index.js
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
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const app = express();
const httpServer = http.createServer(app);
const io = socketIO(httpServer);
function logMonitor(inputs, authOptions, otherOptions) {
const { logFilePath, errorLogFilePath } = inputs;
const { maxLines, port } = otherOptions;
const defaultPort = port || 3000;
if (!logFilePath && errorLogFilePath) {
throw new Error("Error log file path provided, but not the log file path");
}
app.use(express.static(__dirname)); // Serve static files from the current directory
if (authOptions) {
const auth = basicAuth(authOptions);
app.use(auth);
}
app.get('/', (req, res) => {
res.sendFile(__dirname + '/logs.html');
});
app.get('/success', (req, res) => {
res.sendFile(__dirname + '/success.html');
});
app.get('/errors', (req, res) => {
res.sendFile(__dirname + '/errors.html');
});
app.use((req, res, next) => {
return res.send('Reached dead end');
});
function emitLogFileChange(logData, event) {
io.emit(event, logData);
}
function readLastLogLines(filePath, callback) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading log file:', err);
} else {
const lines = data.split('\n');
const lastLines = lines.slice(-maxLines);
callback(lastLines.join('\n'));
}
});
}
if (logFilePath) {
fs.watch(logFilePath, (event, filename) => {
if (event === 'change') {
readLastLogLines(logFilePath, (lastLines) => {
emitLogFileChange(lastLines, 'logFileChange');
});
}
});
}
if (errorLogFilePath) {
fs.watch(errorLogFilePath, (event, filename) => {
if (event === 'change') {
readLastLogLines(errorLogFilePath, (lastLines) => {
emitLogFileChange(lastLines, 'errorLogFileChange');
});
}
});
}
io.on('connection', (socket) => {
console.log('Client connected');
if (errorLogFilePath) {
readLastLogLines(errorLogFilePath, (lastLines) => {
emitLogFileChange(lastLines, 'errorLogFileChange');
});
}
if (logFilePath) {
readLastLogLines(logFilePath, (lastLines) => {
emitLogFileChange(lastLines, 'logFileChange');
});
}
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
httpServer.listen(defaultPort, () => {
console.log(`Logs moniter started on port ${defaultPort}`);
});
}
module.exports = logMonitor