在Debian中进行Node.js日志管理可以通过以下几个步骤来实现:
Node.js生态系统中有多个流行的日志库,如 Winston、Pino、Bunyan 等。Winston是最流行的日志库之一,支持多种传输方式,并且易于配置。
npm install winston
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' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({ format: winston.format.simple() }));
}
const logger = require('./logger');
logger.info('Hello distributed log files!');
npm install log4js
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');
const logger = require('./logger');
logger.info('Hello world!');
sudo apt-get install logrotate
创建一个logrotate配置文件,例如 /etc/logrotate.d/nodejs
:
/path/to/your/nodejs/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0640 root adm
}
logrotate -d /etc/logrotate.d/nodejs # 测试配置是否有误
logrotate -f /etc/logrotate.d/nodejs # 强制运行一次
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-12-31"
通过以上步骤,您可以在Debian系统上有效地管理Node.js应用程序的日志,确保日志的收集、存储、分析和可视化都能顺利进行。