Linux日志下的JS监控实操指南
一 场景与总体思路
二 命令行快速监控
三 用 Node.js 监听日志文件
// logMonitor.js
const fs = require('fs');
const path = require('path');
// 注意:生产环境请处理文件轮转(如 logrotate),本例为简化演示
const logPath = '/var/log/myapp/app.log';
let lastSize = 0;
fs.watchFile(logPath, { interval: 500 }, (curr, prev) => {
if (curr.size > lastSize) {
const stream = fs.createReadStream(logPath, {
start: lastSize,
encoding: 'utf8'
});
stream.on('data', chunk => process.stdout.write(chunk));
stream.on('end', () => { lastSize = curr.size; });
}
});
运行:node logMonitor.js(需对日志文件有读取权限;仅适用于本地日志)。
// lineReader.js
const fs = require('fs');
const readline = require('readline');
const logPath = '/var/log/myapp/app.log';
const rl = readline.createInterface({
input: fs.createReadStream(logPath, { encoding: 'utf8' }),
crlfDelay: Infinity
});
rl.on('line', line => {
if (/ERROR|WARN|Exception/i.test(line)) {
// 可接入告警:sendAlert(line)
console.log('[ALERT]', new Date().toISOString(), line);
}
});
运行:node lineReader.js(同样需读取权限;可按需扩展正则与上报逻辑)。
四 集中化监控与告警
五 排错与运维要点