UNPKG

pm2-log-monitor

Version:

npm package to monitor your server pm2 logs on local

79 lines (65 loc) 2.35 kB
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 startLogMonitor(inputs, authOptions, otherOptions) { const { logFilePath, errorLogFilePath } = inputs; const { maxLines, port } = otherOptions; const defaultPort = port || 3000; 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 + '/index.html'); }); 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')); } }); } fs.watch(logFilePath, (event, filename) => { if (event === 'change') { readLastLogLines(logFilePath, (lastLines) => { emitLogFileChange(lastLines, 'logFileChange'); }); } }); fs.watch(errorLogFilePath, (event, filename) => { if (event === 'change') { readLastLogLines(errorLogFilePath, (lastLines) => { emitLogFileChange(lastLines, 'errorLogFileChange'); }); } }); io.on('connection', (socket) => { console.log('Client connected'); readLastLogLines(errorLogFilePath, (lastLines) => { emitLogFileChange(lastLines, 'errorLogFileChange'); }); readLastLogLines(logFilePath, (lastLines) => { emitLogFileChange(lastLines, 'logFileChange'); }); socket.on('disconnect', () => { console.log('Client disconnected'); }); }); httpServer.listen(defaultPort, () => { console.log(`Server started on port ${defaultPort}`); }); } module.exports = startLogMonitor