合理设置日志级别:
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
transports: [new winston.transports.Console()]
});
使用环境变量控制日志级别:
# 生产环境
export LOG_LEVEL=warn
# 开发环境
export LOG_LEVEL=debug
结构化日志(JSON格式):
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
format: format.json(),
transports: [new transports.Console()]
});
添加时间戳和上下文:
format: format.combine(
format.timestamp(),
format.metadata({ fillExcept: ['message', 'level', 'timestamp'] })
)
使用winston-daily-rotate-file:
const DailyRotateFile = require('winston-daily-rotate-file');
logger.add(new DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
}));
Linux logrotate配置:
# /etc/logrotate.d/nodejs-app
/var/log/nodejs/app.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
copytruncate
}
异步日志记录:
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
// 在中间件中设置上下文
app.use((req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set('requestId', uuid.v4());
next();
});
});
批量写入日志:
const { Writable } = require('stream');
class BatchStream extends Writable {
constructor(options) {
super(options);
this.batch = [];
this.batchSize = options.batchSize || 10;
}
_write(chunk, encoding, callback) {
this.batch.push(chunk);
if (this.batch.length >= this.batchSize) {
this._flushBatch();
}
callback();
}
}
ELK Stack集成:
错误追踪集成:
const { Sentry } = require('@sentry/node');
Sentry.init({
dsn: 'your-dsn',
environment: process.env.NODE_ENV,
tracesSampleRate: 1.0,
});
// 将Sentry与日志系统集成
logger.on('error', (error) => {
Sentry.captureException(error);
});
敏感信息过滤:
const sensitiveFields = ['password', 'token', 'creditCard'];
const redactFormat = format((info) => {
sensitiveFields.forEach(field => {
if (info[field]) {
info[field] = '***REDACTED***';
}
});
return info;
});
日志文件权限设置:
chmod 640 /var/log/nodejs/*.log
chown appuser:appgroup /var/log/nodejs/*.log
日志监控脚本示例:
#!/bin/bash
ERROR_COUNT=$(grep -c "ERROR" /var/log/nodejs/app.log)
if [ "$ERROR_COUNT" -gt 10 ]; then
mail -s "High Error Rate Detected" admin@example.com <<< "Found $ERROR_COUNT errors in the last hour"
fi
Prometheus监控集成:
const client = require('prom-client');
const errorCounter = new client.Counter({
name: 'app_errors_total',
help: 'Total number of application errors'
});
logger.on('error', () => errorCounter.inc());
通过以上优化方法,可以显著提高Linux环境下Node.js应用的日志管理效率、性能和安全性。