在 Linux 上导出 Node.js 日志,常见做法取决于日志是写到哪里的。下面按最常见的几种场景给你一个完整、可操作的方案。
即代码中使用:
console.log()
console.error()
在 Linux 中,这些输出通常是:
stdoutstderrnode app.js > app.log 2>&1
说明:
> app.log:stdout 输出到文件2>&1:stderr 也写入同一文件nohup node app.js > app.log 2>&1 &
日志文件:
app.log
node app.js > stdout.log 2> stderr.log
Node.js 不像 Java 可以动态切日志文件。
pm2(强烈推荐)安装:
npm install -g pm2
启动:
pm2 start app.js --name my-app
查看日志:
pm2 logs my-app
导出日志:
pm2 logs my-app > app.log
日志文件路径:
~/.pm2/logs/
lsof 找到日志文件(如果已写文件)lsof -p <pid> | grep log
示例输出:
node 12345 user 3w REG /home/user/app.log
然后直接拷贝:
cp /home/user/app.log app_backup.log
winston 示例const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('hello world');
导出的日志文件:
combined.log
error.log
docker logs <container_id> > app.log 2>&1
tail -f app.log
tail -n 1000 app.log > app_last_1000.log
| 场景 | 推荐方式 |
|---|---|
| 新项目 | pm2 |
| 临时导出 | node app.js > app.log 2>&1 |
| 已运行 | pm2 logs |
| 生产环境 | winston + pm2 |
| Docker | docker logs |
如果你愿意,可以告诉我:
pm2console.log 还是文件我可以给你精确到命令的定制方案。