在 Linux 环境下导出 JS(JavaScript)日志,常见场景有 Node.js 应用日志、前端 JS 在浏览器中的日志、以及 通过 systemd / Docker 运行的 JS 服务日志。下面按常见情况给你总结几种实用方法。
node app.js > app.log 2>&1
> app.log:重定向 stdout2>&1:stderr 也写入同一文件✅ 适合临时运行或调试
nohup 后台运行并导出日志nohup node app.js > app.log 2>&1 &
查看日志:
tail -f app.log
node app.js >> app-$(date +%Y-%m-%d).log 2>&1
winstonpinolog4jsconst winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' }),
new winston.transports.Console()
]
});
logger.info('这是一条日志');
导出文件:
cat app.log
如果 JS 服务是通过 systemd 启动的:
journalctl -u your-service-name -f
journalctl -u your-service-name > js-service.log
docker logs container_id > js.log 2>&1
docker logs -f container_id
docker inspect --format='{{.LogPath}}' container_id
然后:
cp /var/lib/docker/containers/.../...-json.log js.log
console.log = function (msg) {
fetch('/log', {
method: 'POST',
body: JSON.stringify({ log: msg })
});
};
tail -f app.log # 实时查看
grep "error" app.log # 搜索错误
wc -l app.log # 统计行数
| 场景 | 推荐方式 |
|---|---|
| 本地调试 | node app.js > log.txt |
| 生产运行 | pm2 / systemd |
| 日志管理 | winston + 日志轮转 |
| 容器环境 | Docker logs |
如果你能补充一下:
我可以给你更精确的命令或配置示例。