监控Ubuntu上JavaScript(Node.js)日志的方法
tail命令实时查看日志tail -f是Linux系统最常用的实时日志查看工具,可直接跟踪日志文件的新增内容。例如,若应用日志保存在/var/log/my-js-app.log,执行以下命令即可实时查看:
tail -f /var/log/my-js-app.log
按Ctrl+C可停止监控。此方法适合快速查看实时日志流,无需额外配置。
journalctl查看系统日志若JavaScript应用通过systemd以服务形式运行(如node-app.service),可使用journalctl查看其日志。常用命令:
journalctljournalctl -u your-js-service-namejournalctl -u your-js-service-name -fjournalctl -p err -u your-js-service-nameWinston是Node.js生态中最流行的日志库,支持多传输(文件、控制台、数据库等)、多级别(info/warn/error)、结构化日志。安装与配置示例:
npm install winston
配置文件(如logger.js):
const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 日志级别(info及以上会记录)
format: winston.format.json(), // 结构化日志(便于后续分析)
transports: [
new winston.transports.Console(), // 输出到控制台
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), // 错误日志单独保存
new winston.transports.File({ filename: 'logs/combined.log' }) // 所有日志合并
]
});
module.exports = logger;
在应用中使用:
const logger = require('./logger');
logger.info('Server started on port 3000');
logger.error('Database connection failed');
Winston的优势在于灵活的日志分级和结构化输出,便于后续通过ELK等工具分析。
PM2是Node.js生产环境的常用进程管理工具,内置日志管理、进程守护、负载均衡功能。安装与使用:
npm install pm2 -g
启动应用并记录日志:
pm2 start app.js --name "my-js-app" --log /var/log/my-js-app.log
查看实时日志:
pm2 logs my-js-app
日志轮转配置(避免日志过大):
pm2 set pm2-logrotate:max_size 10M # 单个日志文件最大10MB
pm2 set pm2-logrotate:retain 7 # 保留最近7天日志
PM2适合生产环境,简化了日志管理与进程守护流程。
ELK是开源的日志集中化管理与分析平台,适合大规模应用。搭建步骤:
sudo apt-get install elasticsearch
sudo systemctl start elasticsearch
sudo apt-get install logstash
配置Logstash收集Node.js日志(/etc/logstash/conf.d/nodejs.conf):input {
file {
path => "/var/log/my-js-app.log"
start_position => "beginning"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "nodejs-logs-%{+YYYY.MM.dd}"
}
}
sudo apt-get install kibana
sudo systemctl start kibana
访问http://your-server-ip:5601,通过Kibana创建仪表盘,可视化日志数据(如错误率、请求频率)。若需监控应用性能指标(如请求延迟、内存使用),可结合Prometheus(指标收集)与Grafana(可视化)。步骤:
npm install prom-client
在应用中定义指标(如http_requests_total):const promClient = require('prom-client');
const httpRequestCounter = new promClient.Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'path']
});
app.use((req, res, next) => {
httpRequestCounter.inc({ method: req.method, path: req.path });
next();
});
/etc/prometheus/prometheus.yml,添加Node.js应用作为目标:scrape_configs:
- job_name: 'nodejs'
static_configs:
- targets: ['localhost:9090'] # 应用需暴露Prometheus metrics接口
为避免日志文件过大占用磁盘空间,需配置日志轮转。使用logrotate工具(Ubuntu自带):
/etc/logrotate.d/my-js-app):/var/log/my-js-app.log {
daily # 每天轮转
missingok # 文件不存在时不报错
rotate 7 # 保留最近7份
compress # 压缩旧日志(.gz格式)
notifempty # 空日志不轮转
create 640 root adm # 新日志权限
}
sudo logrotate -f /etc/logrotate.d/my-js-app
此方法可自动化日志管理,减少人工干预。