作为IT工程师,我为您提供几种在Linux环境下管理Node.js日志的有效方案:
console.log('Info message');
console.error('Error message');
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()
}));
}
# 启动应用并记录日志
pm2 start app.js --log-date-format "YYYY-MM-DD HH:mm Z" --log /var/log/node-app.log
# 日志轮转
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30
const bunyan = require('bunyan');
const log = bunyan.createLogger({
name: 'myapp',
streams: [
{
level: 'info',
path: '/var/log/myapp-info.log'
},
{
level: 'error',
path: '/var/log/myapp-error.log'
}
]
});
创建/etc/logrotate.d/node-app
文件:
/var/log/node-app.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
pm2 reloadLogs > /dev/null
endscript
}
# 查看日志
journalctl -u your-node-service -f -n 100
# 按优先级过滤
journalctl -u your-node-service -p err
input {
file {
path => "/var/log/node-app.log"
type => "nodejs"
}
}
<source>
@type tail
path /var/log/node-app.log
pos_file /var/log/node-app.log.pos
tag node.app
format none
</source>
您可以根据项目规模、团队需求选择合适的日志管理方案。对于生产环境,建议至少实现日志轮转和集中化查看功能。