在CentOS上配置Node.js應用程序的日志存儲策略,可以遵循以下幾個步驟:
首先,選擇一個適合Node.js的日志庫。常用的日志庫包括:
winston
pino
morgan
這些庫提供了豐富的日志記錄功能,包括日志級別、日志格式化、日志輪轉等。
以winston
為例,配置日志存儲策略:
const winston = require('winston');
const { createLogger, format, transports } = winston;
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new transports.File({ filename: 'logs/error.log', level: 'error' }),
new transports.File({ filename: 'logs/combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new transports.Console({
format: format.simple()
}));
}
為了防止日志文件過大,可以使用winston-daily-rotate-file
庫來實現日志輪轉:
const { createLogger, format, transports } = winston;
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: 'logs/application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
transport,
new transports.Console({
format: format.simple()
})
]
});
定期監控日志文件的大小和數量,并設置自動清理策略??梢允褂?code>cron任務來定期清理舊日志文件:
# 每天凌晨2點清理7天前的日志文件
0 2 * * * find /path/to/logs -type f -name "*.log" -mtime +7 -exec rm -f {} \;
如果需要將日志發送到系統日志服務(如syslog
),可以使用winston-syslog
庫:
const { createLogger, format, transports } = winston;
const Syslog = require('winston-syslog');
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new Syslog({
host: 'localhost',
port: 514,
protocol: 'udp4'
}),
new transports.Console({
format: format.simple()
})
]
});
如果Node.js應用程序通過Nginx或Apache反向代理,可以配置這些服務器來處理日志文件,以便更好地管理和監控日志。
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
通過以上步驟,你可以在CentOS上配置Node.js應用程序的日志存儲策略,確保日志文件得到有效管理和監控。