温馨提示×

如何过滤Debian Nodejs日志

小樊
42
2026-08-11 23:10:49
栏目: 编程语言

在 Debian 上过滤 Node.js 日志,取决于日志写在哪里(stdout、文件、systemd、PM2、Docker 等)。下面按常见场景给你一套实用做法。


一、Node.js 直接运行(stdout / stderr)

1️⃣ 使用 grep 过滤

node app.js | grep "ERROR"

只显示包含 ERROR 的日志。

忽略大小写:

node app.js | grep -i error

过滤多个关键词:

node app.js | grep -E "ERROR|WARN"

排除某些日志:

node app.js | grep -v "healthcheck"

二、日志输出到文件

示例

node app.js > app.log 2>&1

实时过滤查看

tail -f app.log | grep "ERROR"

查看某段时间日志

grep "2026-01-21 10:" app.log

按级别过滤(常见格式)

grep -E "error|warn" app.log

三、使用 systemd(Debian 常见)

如果 Node.js 是通过 systemd 管理的:

查看日志

journalctl -u your-node-service.service

实时查看

journalctl -u your-node-service.service -f

过滤 ERROR

journalctl -u your-node-service.service | grep ERROR

只看今天

journalctl -u your-node-service.service --since today

四、使用 PM2(非常常见)

查看日志

pm2 logs

只看 error 日志

pm2 logs --err

实时过滤

pm2 logs | grep "ERROR"

查看指定应用

pm2 logs app-name

五、Docker 中运行 Node.js

查看实时日志

docker logs -f container_id

过滤错误

docker logs container_id 2>&1 | grep ERROR

六、Node.js 日志最佳实践(推荐)

✅ 使用日志库

例如 winston / pino

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

这样你可以:

grep ERROR error.log

七、常用组合总结

场景 推荐命令
实时查看 tail -f app.log
过滤错误 grep ERROR app.log
systemd journalctl -u xxx -f
PM2 pm2 logs --err
Docker docker logs -f xxx

如果你愿意,可以告诉我:

  • ✅ Node.js 是怎么运行的(systemd / PM2 / Docker / 直接运行)
  • ✅ 日志格式示例

我可以帮你定制一条最精准的过滤命令

0