在 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。
winstonwinston 是一个功能强大的日志库,支持多种传输方式(如文件、控制台、HTTP 等)。
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');
pinopino 是一个高性能的日志库,适合需要高吞吐量的应用。
const pino = require('pino');
const prettyPrint = require('pino-pretty');
const logger = pino({
level: 'info'
});
// 在控制台中使用 prettyPrint
prettyPrint(logger);
logger.info('Application started');
为了防止日志文件过大,可以使用日志轮转工具,如 logrotate。
logrotate创建一个 logrotate 配置文件 /etc/logrotate.d/myapp:
/path/to/your/app.log {
daily
missingok
rotate 7
compress
notifempty
create 640 root adm
}
这个配置会每天轮转一次日志文件,并保留最近 7 天的日志文件。
结合监控工具(如 Prometheus、Grafana)和报警系统(如 Alertmanager),可以实时监控日志并设置报警规则。
确保日志文件的安全性,避免敏感信息泄露。可以使用加密工具对日志文件进行加密。
gpg 加密日志文件gpg --symmetric --cipher-algo AES256 app.log
解密时使用:
gpg --decrypt app.log.gpg > app.log
通过以上方法,你可以在 Linux 系统中有效地管理和监控 Node.js 应用程序的日志。