温馨提示×

ubuntu nodejs日志啥格式

小樊
43
2026-09-12 10:34:34
栏目: 编程语言

在 Ubuntu 上,Node.js 本身的日志格式并没有统一强制标准,主要取决于你怎么运行 Node.js 以及用了什么日志库。下面按常见情况给你梳理一下:


一、Node.js 默认输出(console.log / console.error)

如果你直接在 Ubuntu 跑:

node app.js

代码里写:

console.log("hello");
console.error("something wrong");

输出格式

就是纯文本,没有时间戳:

hello
something wrong
  • console.log → 标准输出(stdout)
  • console.error → 标准错误(stderr)

二、Ubuntu systemd 管理的 Node.js 服务

如果你用 systemd(最常见生产环境):

systemctl status my-node-app
journalctl -u my-node-app

日志格式(journald)

Jun 25 10:12:34 ubuntu node[12345]: hello
Jun 25 10:12:35 ubuntu node[12345]: something wrong

特点:

  • 自动带 时间
  • 主机名
  • 进程名 / PID
  • 格式由 systemd 控制,不是 Node.js 控制

三、使用日志库(生产推荐)

1️⃣ Winston(最常用)

默认格式示例:

{"level":"info","message":"hello","timestamp":"2024-06-25T10:12:34.123Z"}

或自定义成:

2024-06-25 10:12:34 [INFO] hello

2️⃣ Pino(高性能)

默认是 JSON 行

{"level":30,"time":1719319954123,"msg":"hello"}

适合:

  • 容器
  • ELK / Loki / 日志采集

四、PM2 管理的 Node.js

如果你用 PM2:

pm2 logs

格式示例:

YYYY-MM-DD HH:mm:ss: hello

PM2 会自动加时间。


五、总结一张表

运行方式 日志格式
node app.js 纯文本
systemd 时间 + 主机 + 进程
console.log 无时间
Winston 可 JSON / 文本
Pino JSON
PM2 时间 + 文本

如果你愿意,我可以:

  • 给你 推荐一套 Ubuntu + Node.js 日志方案
  • 或帮你 写一段 Winston / Pino 配置
  • 或讲 怎么接 journald / Docker / ELK

你现在是 开发环境还是生产环境

0