温馨提示×

ubuntu nodejs日志怎开启

小樊
45
2026-09-30 15:52:39
栏目: 编程语言

在 Ubuntu 上开启 Node.js 日志,通常分几种场景。下面按常见用法给你说明:


一、最简单:在代码里打印日志(推荐)

Node.js 自带 console,直接输出即可:

console.log('普通日志');
console.error('错误日志');

运行:

node app.js

查看日志:

node app.js > app.log 2>&1
  • >:标准输出
  • 2>&1:错误也写入

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

1. winston(最常用)

npm install winston

示例:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'app.log' }),
    new winston.transports.Console()
  ]
});

logger.info('服务启动');

三、PM2 管理 Node.js(Ubuntu 常用)

安装

npm install -g pm2

启动

pm2 start app.js

查看日志

pm2 logs

指定日志文件

pm2 start app.js --log /var/log/node/app.log

四、Systemd 方式(Ubuntu 服务)

如果你用 systemd 运行 Node:

# /etc/systemd/system/node.service
[Service]
ExecStart=/usr/bin/node /home/user/app.js
StandardOutput=syslog
StandardError=syslog

查看日志:

journalctl -u node.service

五、Nginx 反向代理日志(可选)

如果你用 Nginx:

tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

总结

场景 方法
本地调试 console.log
生产 winston + pm2
系统服务 systemd journal

如果你能说下:

  • 是 本地还是服务器
  • 用没用 PM2 / Docker / Nginx

我可以给你更精确的配置。

0 踩