作为IT工程师,我可以提供一套系统的方法来利用JavaScript日志优化Linux服务器性能。以下是详细方案:
# 安装Node.js日志收集代理
npm install -g winston
npm install -g winston-syslog
// 使用Winston创建结构化日志
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: '/var/log/node-app/combined.log' }),
new winston.transports.Syslog()
]
});
// 记录内存使用情况
setInterval(() => {
const memoryUsage = process.memoryUsage();
logger.info('Memory usage', {
rss: memoryUsage.rss,
heapTotal: memoryUsage.heapTotal,
heapUsed: memoryUsage.heapUsed,
external: memoryUsage.external
});
}, 60000); // 每分钟记录一次
// Express中间件记录响应时间
app.use((req, res, next) => {
const start = process.hrtime();
res.on('finish', () => {
const duration = process.hrtime(start);
const responseTime = duration[0] * 1000 + duration[1] / 1000000;
logger.info('Request completed', {
method: req.method,
url: req.url,
status: res.statusCode,
responseTime: responseTime
});
});
next();
});
# 安装Filebeat收集日志
sudo apt-get install filebeat
配置Filebeat (/etc/filebeat/filebeat.yml
):
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/node-app/*.log
output.elasticsearch:
hosts: ["localhost:9200"]
内存泄漏检测:
慢请求分析:
# 使用jq分析慢请求
cat /var/log/node-app/combined.log | jq 'select(.responseTime > 500)'
CPU密集型操作:
// 记录CPU密集型任务
logger.profile('heavyOperation');
// 执行耗时操作
heavyOperation();
logger.profile('heavyOperation');
#!/bin/bash
# 基于Node.js内存使用自动扩容
MEM_THRESHOLD=80
CURRENT_MEM=$(cat /var/log/node-app/combined.log | jq -r 'select(.heapUsed) | .heapUsed' | tail -1)
if (( $(echo "$CURRENT_MEM > $MEM_THRESHOLD" | bc -l) )); then
# 触发扩容操作
kubectl scale deployment node-app --replicas=2
fi
// 当内存超过阈值时优雅重启
setInterval(() => {
const memoryUsage = process.memoryUsage();
const usedPercentage = (memoryUsage.heapUsed / memoryUsage.heapTotal) * 100;
if (usedPercentage > 90) {
logger.warn('High memory usage detected, initiating graceful restart');
server.close(() => {
process.exit(1);
});
}
}, 300000); // 每5分钟检查一次
日志轮转:
# 使用logrotate管理日志
sudo nano /etc/logrotate.d/node-app
配置内容:
/var/log/node-app/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 root adm
sharedscripts
postrotate
systemctl restart node-app
endscript
}
敏感信息过滤:
// 在记录前过滤敏感数据
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format((info) => {
if (info.password) {
info.password = '***REDACTED***';
}
return info;
})(),
winston.format.json()
)
}));
通过以上方法,您可以系统性地利用JavaScript日志来监控和优化Linux服务器上的Node.js应用性能。关键是要建立持续的监控、分析和优化循环。