在Debian系統上管理Node.js日志通常涉及以下幾個方面:選擇合適的日志庫、配置日志級別、日志格式化、日志輸出、日志輪換和日志管理工具的使用。以下是詳細的管理方法:
Winston配置示例:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console(),
],
});
logger.info('This is an info log.');
logger.error('This is an error log.');
Bunyan配置示例:
const bunyan = require('bunyan');
const logger = bunyan.createLogger({
name: 'myapp',
streams: [
{ level: 'info', stream: process.stdout },
{ level: 'error', path: 'app-error.log' },
],
});
logger.info('This is an info log.');
logger.error('This is an error log.');
正確使用日志級別(如trace、debug、info、warn、error、fatal)至關重要,可以根據需要過濾日志內容。
根據實際需求,選擇合適的日志格式。對于調試和開發,簡單的文本日志足夠;對于生產環境,建議使用JSON格式,便于機器處理和分析。
使用日志庫的特性或外部工具(如logrotate)來管理日志文件大小,自動刪除舊日志或歸檔。
logrotate配置示例:
/path/to/your/nodejs/app/logs/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 root adm
}
這個配置表示每天輪轉日志文件,保留最近7天的日志,并對舊日志文件進行壓縮。
pm2:一個常用于生產環境中的Node.js進程管理工具,提供進程守護、負載均衡等高級功能,并內置了日志管理功能。
pm2日志管理命令:
pm2 logs # 查看所有進程的日志
pm2 logs aggregate # 聚合所有進程的日志
在Debian系統中,可以使用以下命令行工具來查看系統日志文件:
通過以上方法,可以有效地在Debian系統上管理Node.js日志,確保應用程序的可靠性和可維護性。