插件窝 干货文章 Linux下JS日志分析有哪些技巧

Linux下JS日志分析有哪些技巧

日志 log app bash 869    来源:    2025-05-06

Linux下JS日志分析技巧

在Linux环境下分析JavaScript日志有多种方法和工具,以下是一些实用的技巧:

1. 基础命令行工具

grep/fgrep

# 查找特定错误
grep -i "error" app.log

# 查找特定函数调用
grep "functionName" app.log

# 使用正则表达式查找
grep -E "TypeError|ReferenceError" app.log

awk

# 统计错误出现次数
awk '/error/ {count++} END {print count}' app.log

# 提取特定字段
awk '{print $1, $5}' app.log

sed

# 过滤时间范围内的日志
sed -n '/2023-01-01 10:00/,/2023-01-01 11:00/p' app.log

2. 专用日志分析工具

jq (处理JSON格式日志)

# 解析JSON日志
cat app.log | jq '. | {timestamp: .time, message: .msg, level: .level}'

# 过滤特定级别的日志
cat app.log | jq 'select(.level == "error")'

logrotate

# 配置日志轮转
/etc/logrotate.d/your_app_config

3. Node.js特定工具

pino (高性能日志记录器)

# 使用pino-pretty美化日志
node app.js | pino-pretty

winston

# 分析winston格式日志
grep -i "warn" app.log | jq '.'

4. 实时日志监控

tail

# 实时监控日志
tail -f app.log | grep --line-buffered "error"

multitail

# 同时监控多个日志文件
multitail -cS apache /var/log/apache.log -cS app /var/log/app.log

5. 高级分析技巧

错误模式识别

# 查找常见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

6. 日志可视化

使用ELK Stack (Elasticsearch, Logstash, Kibana)

# 配置Logstash管道处理JS日志
input {
  file {
    path => "/var/log/app.log"
    start_position => "beginning"
  }
}
filter {
  json {
    source => "message"
  }
}
output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}

使用Grafana + Loki

# 使用LogCLI查询Loki中的日志
logcli query '{app="your-js-app"} |= "error"'

7. 自定义分析脚本

// 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}`);
});

最佳实践

  1. 结构化日志:使用JSON格式记录日志,便于解析和分析
  2. 日志分级:合理使用error、warn、info、debug等级别
  3. 包含上下文:每条日志应包含足够上下文信息
  4. 敏感信息过滤:避免记录密码等敏感信息
  5. 定期归档:设置日志轮转策略,避免磁盘空间问题

通过组合使用这些工具和技术,可以高效地分析和排查JavaScript应用在Linux环境下的问题。