在Linux环境中,Node.js应用程序的日志存储策略对于确保系统的稳定性和可维护性至关重要。以下是一些常见的日志存储策略:
为了避免日志文件过大,可以使用日志轮转工具,如logrotate。logrotate可以定期压缩、备份和删除旧日志文件。
/path/to/your/nodejs.log {
daily
rotate 7
compress
delaycompress
notifempty
create 0640 root adm
}
使用集中式日志管理系统,如ELK Stack(Elasticsearch, Logstash, Kibana)或Fluentd,可以更方便地收集、存储和分析日志。
<source>
@type tail
path /path/to/your/nodejs.log
pos_file /var/log/fluentd/nodejs.log.pos
tag nodejs
<parse>
@type none
</parse>
</source>
<match nodejs>
@type elasticsearch
host localhost
port 9200
logstash_format true
flush_interval 10s
</match>
根据日志类型或功能模块分割日志文件,便于管理和分析。
const fs = require('fs');
const path = require('path');
const logDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const accessLogStream = fs.createWriteStream(path.join(logDir, 'access.log'), { flags: 'a' });
const errorLogStream = fs.createWriteStream(path.join(logDir, 'error.log'), { flags: 'a' });
// 在Express中使用
app.use((req, res, next) => {
accessLogStream.write(`${req.method} ${req.url} ${res.statusCode}\n`);
next();
});
app.use((err, req, res, next) => {
errorLogStream.write(`${new Date().toISOString()} - ${err.stack}\n`);
next(err);
});
设置监控系统,如Prometheus和Grafana,实时监控日志并设置告警规则。
groups:
- name: nodejs_logs
rules:
- alert: HighErrorRate
expr: rate(nodejs_error_count[5m]) > 0.1
for: 1m
labels:
severity: critical
annotations:
summary: "High error rate detected in Node.js logs"
description: "The error rate has been above 0.1 for the last minute."
确保日志文件的安全性,避免敏感信息泄露。可以使用加密工具对日志文件进行加密,并限制访问权限。
sudo chown root:adm /path/to/your/nodejs.log
sudo chmod 640 /path/to/your/nodejs.log
sudo apt-get install logrotate
sudo cp /etc/logrotate.d/default /etc/logrotate.d/nodejs
sudo sed -i 's/^copytruncate$/rotate/' /etc/logrotate.d/nodejs
通过以上策略,可以有效地管理和存储Node.js应用程序的日志,确保系统的稳定性和可维护性。