CentOS上Node.js日志配置与管理
一 核心方案与工具
二 应用内日志配置示例
// logger.js
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
format.json()
),
transports: [
new transports.File({ filename: 'logs/error.log', level: 'error' }),
new transports.File({ filename: 'logs/combined.log' }),
new transports.Console()
]
});
module.exports = logger;
// logger-daily.js
const { createLogger, format, transports } = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
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.toUpperCase()}: ${message}`;
})
),
transports: [
new DailyRotateFile({
filename: 'logs/app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
})
]
});
module.exports = logger;
// logger-log4js.js
const log4js = require('log4js');
log4js.configure({
appenders: {
out: { type: 'console' },
app: {
type: 'dateFile',
filename: 'logs/app',
pattern: '.yyyy-MM-dd.log',
compress: true,
alwaysIncludePattern: true
}
},
categories: {
default: { appenders: ['out', 'app'], level: 'info' }
}
});
const logger = log4js.getLogger();
module.exports = logger;
三 系统级日志轮转与保留策略
/path/to/your/nodejs/app/logs/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 root root
}
四 进程管理与集中式日志
const { createLogger, transports } = require('winston');
const SyslogTransport = require('winston-syslog').SyslogTransport;
const logger = createLogger({
level: 'info',
transports: [
new SyslogTransport({
host: '192.0.2.10', // 远程 rsyslog 地址
port: 514,
protocol: 'udp4'
})
]
});
五 日常运维与最佳实践