在 Linux 上监控 Node.js 应用程序的日志有多种方法,以下是一些常用的工具和命令:
tail
命令实时查看日志tail -f
命令可以用来实时查看日志文件的末尾内容。例如,要查看名为 app.log
的日志文件,可以使用以下命令:
tail -f app.log
这将持续显示 app.log
文件的末尾内容,直到你通过 Ctrl+C 组合键结束命令。
watch
命令定期执行命令watch
命令可以定期执行指定的命令,并显示命令的输出结果。例如,每隔 2 秒查看当前目录下的文件:
watch -n 2 ls
在 Node.js HTTP 服务器中的应用,可以通过 watch
命令实时查看服务器日志文件的变化:
watch -n 1 tail -f /path/to/your/server.log
Winston 和 Bunyan 是 Node.js 中流行的日志记录库,它们提供了灵活的日志记录级别、格式化和传输方式。例如,使用 Winston 记录日志:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' })
]
});
logger.info('Server started on port 3000');
logger.error('Database connection failed');
journalctl
命令查看系统日志在基于 Systemd 的 Linux 系统中,可以使用 journalctl
命令查看与 Node.js 相关的系统日志:
journalctl -u your-nodejs-service-name -t
其中 your-nodejs-service-name
是你的 Node.js 服务名称。
通过上述方法,你可以在 Linux 上有效地监控和管理 Node.js 应用程序的日志。