在 Linux 下用 Node.js 解析日志,通常取决于日志格式(plain text、JSON、CSV、Nginx/Apache 格式等)。下面按常见场景给你一套实用方案。
const fs = require('fs');
const logs = fs.readFileSync('/var/log/app.log', 'utf8')
.split('\n')
.filter(Boolean);
logs.forEach(line => {
console.log(parseLine(line));
});
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('/var/log/app.log'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
parseLine(line);
});
✅ 适合 GB 级日志文件
示例日志:
2024-01-12 10:22:33 [ERROR] user 123 failed login
function parseLine(line) {
const regex = /^(\S+) (\S+) \[(\w+)\] (.+)$/;
const match = line.match(regex);
if (!match) return null;
return {
date: match[1],
time: match[2],
level: match[3],
message: match[4]
};
}
日志示例:
{"time":"2024-01-12T10:22:33Z","level":"error","msg":"login failed","uid":123}
function parseLine(line) {
try {
return JSON.parse(line);
} catch {
return null;
}
}
✅ 结构化、易分析、易扩展
默认格式:
127.0.0.1 - - [12/Jan/2024:10:22:33 +0000] "GET /api HTTP/1.1" 200 1234
const regex = /^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d+) (\d+)/;
function parseNginx(line) {
const m = line.match(regex);
if (!m) return null;
return {
ip: m[1],
time: m[2],
method: m[3],
url: m[4],
status: m[6],
size: m[7]
};
}
const errorCount = {};
rl.on('line', (line) => {
const log = parseLine(line);
if (log?.level === 'ERROR') {
errorCount[log.message] = (errorCount[log.message] || 0) + 1;
}
});
rl.on('close', () => {
console.log(errorCount);
});
const glob = require('glob');
glob('/var/log/app/*.log', (err, files) => {
files.forEach(file => {
// 流式解析
});
});
✅ 日志尽量用 JSON
✅ 使用 stream 防止内存爆炸
✅ 配合 logrotate
✅ 错误日志单独文件
如果你愿意,可以:
我可以直接帮你写可用的解析脚本。