debian

如何自动化Debian JS日志分析

小樊
38
2025-12-14 09:35:29
栏目: 编程语言

Debian JS日志自动化分析实操方案

一 架构与准备

二 方案一 轻量自动化脚本分析

// analyze.js
const fs = require('fs');
const path = require('path');
const readline = require('readline');

const logFile = process.argv[2] || '/var/log/your-js-app.log';
const since = process.argv[3]; // 可选 ISO8601 时间,如 2025-12-14T00:00:00Z
const errorThreshold = parseInt(process.env.ERROR_THRESHOLD || '10', 10);

const rl = readline.createInterface({ input: fs.createReadStream(logFile), crlfDelay: Infinity });
const counts = { error: 0, warn: 0, info: 0 };
const topErrors = new Map();
let lines = 0;

rl.on('line', (line) => {
  lines++;
  let rec;
  try { rec = JSON.parse(line); } catch (e) { return; }

  // 时间过滤
  if (since && rec.time && new Date(rec.time) < new Date(since)) return;

  const level = String(rec.level || 'info').toLowerCase();
  if (counts[level] !== undefined) counts[level]++;

  if (level === 'error' && rec.msg) {
    const k = rec.msg.split(/\s+/, 5).join(' '); // 简单聚类
    topErrors.set(k, (topErrors.get(k) || 0) + 1);
  }
});

rl.on('close', () => {
  console.log(new Date().toISOString(), 'Processed lines:', lines);
  console.log('Counts:', counts);
  console.log('Top errors:');
  [...topErrors.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
    .forEach(([msg, n]) => console.log(`  ${n}\t${msg}`));

  if (counts.error >= errorThreshold) {
    console.error('ALERT: error count', counts.error, '>= threshold', errorThreshold);
    // TODO: 发送告警(如 curl 到 webhook、邮件等)
  }
});
# 安装依赖
sudo apt update && sudo apt install -y nodejs npm
sudo npm i -D chalk

# 每日 02:00 分析昨天的日志
0 2 * * * /usr/bin/node /opt/scripts/analyze.js /var/log/your-js-app.log \
  "$(date -d 'yesterday 00:00:00' -Iseconds)" >> /var/log/js-analysis.log 2>&1

三 方案二 集中化平台分析 ELK

# 导入 Elastic GPG 并添加 APT 源(示例为 7.x,按需调整)
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-7.x.list
sudo apt-get update
sudo apt-get install -y elasticsearch logstash kibana

sudo systemctl enable --now elasticsearch logstash kibana
input {
  file {
    path => "/var/log/your-js-app.log"
    start_position => "beginning"
    sincedb_path => "/var/lib/logstash/sincedb-js"
    codec => "json"
  }
}

filter {
  # 若日志为 Common Log Format,可用 grok 解析
  # grok { match => { "message" => "%{COMBINEDAPACHELOG}" } }

  date {
    match => [ "time", "ISO8601", "yyyy-MM-dd HH:mm:ss.SSS" ]
    target => "@timestamp"
  }

  mutate {
    remove_field => [ "host", "path" ]  # 视情况保留
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "js-logs-%{+YYYY.MM.dd}"
  }
}

四 日志轮转与资源监控

/var/log/your-js-app.log {
  daily
  rotate 14
  compress
  delaycompress
  missingok
  notifempty
  create 0644 node node
  sharedscripts
  postrotate
    systemctl reload your-js-app.service >/dev/null 2>&1 || true
  endscript
}

五 告警与持续优化

0
看了该问题的人还看了