在 Linux 上“开启 Node.js 日志”通常有几种理解,下面按常见场景给你说明,你可以对号入座。
Node.js 默认不会自动写日志文件,需要你在代码里输出日志。
console.log('正常日志');
console.error('错误日志');
运行:
node app.js > app.log 2>&1
>:标准输出2>&1:错误也写入日志npm install winston
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' })
]
});
logger.info('服务启动');
PM2 会自动管理 Node.js 日志。
npm install pm2 -g
pm2 start app.js
查看日志:
pm2 logs
日志文件位置:
~/.pm2/logs/
如果你是 systemd 服务运行 Node.js:
[Unit]
Description=Node App
[Service]
ExecStart=/usr/bin/node /opt/app/app.js
Restart=always
User=node
[Install]
WantedBy=multi-user.target
systemctl start yourapp
journalctl -u yourapp -f
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
NODE_DEBUG=* node app.js
| 场景 | 推荐方式 |
|---|---|
| 本地开发 | console |
| 生产环境 | PM2 / winston |
| 系统服务 | systemd + journalctl |
如果你能说明:
我可以给你更精确的配置示例。