在Linux环境下分析JavaScript日志有多种方法和工具,以下是一些实用的技巧:
# 查找特定错误
grep -i "error" app.log
# 查找特定函数调用
grep "functionName" app.log
# 使用正则表达式查找
grep -E "TypeError|ReferenceError" app.log
# 统计错误出现次数
awk '/error/ {count++} END {print count}' app.log
# 提取特定字段
awk '{print $1, $5}' app.log
# 过滤时间范围内的日志
sed -n '/2023-01-01 10:00/,/2023-01-01 11:00/p' app.log
# 解析JSON日志
cat app.log | jq '. | {timestamp: .time, message: .msg, level: .level}'
# 过滤特定级别的日志
cat app.log | jq 'select(.level == "error")'
# 配置日志轮转
/etc/logrotate.d/your_app_config
# 使用pino-pretty美化日志
node app.js | pino-pretty
# 分析winston格式日志
grep -i "warn" app.log | jq '.'
# 实时监控日志
tail -f app.log | grep --line-buffered "error"
# 同时监控多个日志文件
multitail -cS apache /var/log/apache.log -cS app /var/log/app.log
# 查找常见JS错误模式
grep -E "Cannot read property|undefined is not a function|Unexpected token" app.log
# 查找执行时间过长的操作
awk '/Execution time/ {if ($NF > 1000) print}' app.log
# 按小时统计错误数量
awk '{print $1}' app.log | cut -d: -f1 | sort | uniq -c
# 配置Logstash管道处理JS日志
input {
file {
path => "/var/log/app.log"
start_position => "beginning"
}
}
filter {
json {
source => "message"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
}
}
# 使用LogCLI查询Loki中的日志
logcli query '{app="your-js-app"} |= "error"'
// analyze.js - 自定义日志分析脚本
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('app.log'),
crlfDelay: Infinity
});
let errorCount = 0;
rl.on('line', (line) => {
if (line.includes('ERROR')) {
errorCount++;
console.log(`Error found: ${line}`);
}
}).on('close', () => {
console.log(`Total errors: ${errorCount}`);
});
通过组合使用这些工具和技术,可以高效地分析和排查JavaScript应用在Linux环境下的问题。