在 Ubuntu 上,Node.js 本身没有固定、统一的“官方日志格式”。日志长什么样,主要取决于你用的运行方式、日志库、以及进程管理器。下面按常见场景给你梳理:
node app.js
console.logconsole.errorhello world
Error: something wrong
at app (/app.js:10:3)
✅ 特点:
如果你用:
systemctl start my-node-app
journalctl -u my-node-app
Aug 21 10:32:01 ubuntu node[1234]: Server started on port 3000
Aug 21 10:32:05 ubuntu node[1234]: Error: DB connection failed
✅ 特点:
pm2 start app.js
pm2 logs
YYYY-MM-DD HH:mm:ss: 信息
示例:
2024-08-21 10:32:01: App listening on 3000
2024-08-21 10:32:05: Unhandled rejection detected
✅ 特点:
~/.pm2/logs/
winstonpinobunyanlogger.info('User logged in', { userId: 1 });
{
"level": "info",
"message": "User logged in",
"userId": 1,
"timestamp": "2024-08-21T10:32:01.123Z"
}
✅ 生产环境推荐格式:
level / time / message / contextNode 日志 → 应用日志
Nginx 日志 → 访问日志
IP - - [time] "GET /api HTTP/1.1" 200 123
| 场景 | 日志格式 | 是否带时间 |
|---|---|---|
| node 直接运行 | 纯文本 | ❌ |
| systemd | 系统日志格式 | ✅ |
| PM2 | 时间戳 + 文本 | ✅ |
| Winston/Pino | JSON / 自定义 | ✅ |
| Nginx | 访问日志 | ✅ |
如果你能补充说明:
我可以给你更精确的日志格式或配置示例。