在Debian系统上管理Node.js应用程序的日志,通常涉及以下几个方面:选择合适的日志库、配置日志级别、日志的存储和轮转、以及使用日志管理工具。以下是详细的步骤和建议:
Node.js生态系统中有多个流行的日志库,如Winston、Pino、Bunyan等。Winston是最流行的日志库之一,支持多种传输方式,并且易于配置。
npm install winston
创建一个日志配置文件,例如 logger.js
:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple(),
}));
}
module.exports = logger;
const logger = require('./logger');
logger.info('Hello distributed log files!');
npm install log4js
创建一个日志配置文件,例如 logger.js
:
var log4js = require('log4js');
log4js.configure({
appenders: {
console: { type: 'console' },
cheeseLogs: { type: 'file', filename: 'logs/cheese.log', category: 'cheese' },
},
categories: { default: { appenders: ['console', 'cheeseLogs'], level: 'info' } },
});
var logger = log4js.getLogger('cheese');
module.exports = logger;
const logger = require('./logger');
logger.info('Hello world!');
logrotate是一个用于管理日志文件的工具,可以自动轮转、压缩和删除旧的日志文件。
sudo apt-get install logrotate
创建一个logrotate配置文件,例如 /etc/logrotate.d/nodejs
:
/path/to/your/nodejs/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0644 root root
}
logrotate -d /etc/logrotate.d/nodejs # 测试配置是否有误
logrotate -f /etc/logrotate.d/nodejs # 强制运行一次
pm2是一个进程管理器,可以方便地管理Node.js应用程序的日志。
sudo npm install -g pm2
pm2 start app.js
pm2 logs
如果需要分别查看错误日志和正常日志,可以配置pm2的日志文件:
{
"apps": [
{
"name": "my-app",
"script": "app.js",
"error_file": "err.log",
"out_file": "out.log"
}
]
}
然后使用以下命令查看日志:
pm2 logs my-app
Debian系统使用systemd作为日志系统,可以使用 journalctl
命令查看系统日志。
journalctl
journalctl -u 服务名称
journalctl --since "2021-01-01" --until "2021-01-31"
通过以上步骤,您可以在Debian系统上有效地管理Node.js应用程序的日志,确保日志的收集、存储、分析和可视化都能顺利进行。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>