在 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 應用程序的日志。