Linux系统为Node.js应用提供了多样化的日志管理方案,通过合理配置可显著提升运维效率。本文将详细介绍几种实用方法与操作步骤。

console 模块Node.js自带的console模块能满足基础日志需求,通过文件流可实现持久化存储。
const fs = require('fs');
const path = require('path');
const logStream = fs.createWriteStream(path.join(__dirname, 'app.log'), { flags: 'a' });
function log(message) {
const timestamp = new Date().toISOString();
logStream.write(`${timestamp} - ${message}n`);
}
log('Application started');
专业日志库如winston和pino能提供更强大的日志处理能力。
winston该库支持多通道日志传输,可通过JSON格式记录结构化数据。
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
logger.info('Application started');
pino针对高性能场景设计的日志库,配合pino-pretty可优化控制台输出。
const pino = require('pino');
const prettyPrint = require('pino-pretty');
const logger = pino({
level: 'info'
});
prettyPrint(logger);
logger.info('Application started');
采用logrotate工具可自动维护日志文件体积,避免存储空间耗尽。
logrotate在/etc/logrotate.d/myapp中配置轮转策略:
/path/to/your/app.log {
daily
missingok
rotate 7
compress
notifempty
create 640 root adm
}
该配置实现每日轮转,保留7天日志并启用压缩功能。
结合Prometheus和Grafana构建可视化监控体系,能实时掌握日志动态。
采用gpg加密可有效保护日志中的敏感信息。
gpg 加密日志文件gpg --symmetric --cipher-algo AES256 app.log
解密时执行:
gpg --decrypt app.log.gpg > app.log
通过系统化的日志管理方案,不仅能提升Node.js应用的可维护性,还能增强系统安全性与稳定性。