温馨提示×

nodejs linux日志怎么搜索

小樊
35
2026-09-02 12:55:03
栏目: 编程语言

在 Linux 环境下用 Node.js 相关日志进行搜索,常见做法分几类:直接用 Linux 命令Node.js 脚本读取日志使用日志库/日志系统。下面按场景说明。


一、直接用 Linux 命令(最常用)

1. 搜索关键字

grep "error" app.log

2. 忽略大小写

grep -i "timeout" app.log

3. 显示行号

grep -n "ECONNREFUSED" app.log

4. 实时搜索(Node 服务运行中)

tail -f app.log | grep "error"

5. 按时间范围(如今天)

grep "2026-01-21" app.log

6. 多文件搜索

grep -r "TypeError" logs/

二、Node.js 日志文件搜索脚本

适合需要在代码里分析日志:

const fs = require('fs');
const readline = require('readline');

async function searchLog(file, keyword) {
  const rl = readline.createInterface({
    input: fs.createReadStream(file),
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    if (line.includes(keyword)) {
      console.log(line);
    }
  }
}

searchLog('app.log', 'error');

三、Node.js 日志库自带搜索能力

常用日志库

  • winston
  • pino
  • bunyan

例如 bunyan 自带命令行工具:

bunyan app.log -c 'level >= 30'

四、结构化日志(推荐)

如果是 JSON 日志(pino / bunyan):

cat app.log | jq 'select(.level == "error")'

五、生产环境建议

  • 日志按天切割(winston-daily-rotate-file
  • 重要服务接 ELK / Loki / Grafana
  • 避免 console.log 直接打生产日志

如果你有具体场景(比如:PM2 日志 / Docker 日志 / K8s 日志 / 某个 Node 框架),我可以给你更精确的命令。

0