通過日志監控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
。
Winston是一個功能強大的日志庫,支持多種傳輸方式(如文件、控制臺、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' })
]
});
logger.info('Application started');
Pino是一個高性能的日志庫,適合需要高吞吐量的應用。
const pino = require('pino');
const logger = pino({ level: 'info' });
logger.info('Application started');
為了更好地管理和分析日志,可以使用日志聚合工具,如ELK Stack(Elasticsearch, Logstash, Kibana)或Graylog。
ELK Stack是一個流行的日志聚合和分析解決方案。
你可以使用filebeat
將Node.js應用的日志發送到Logstash。
# filebeat.yml
filebeat.inputs:
- type: log
enabled: true
paths:
- /path/to/your/nodejs/app.log
output.logstash:
hosts: ["localhost:5044"]
然后在Logstash中配置輸入和輸出插件,將日志發送到Elasticsearch。
# logstash.conf
input {
beats {
port => 5044
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "nodejs-app-%{+YYYY.MM.dd}"
}
}
最后,在Kibana中創建儀表板來可視化日志數據。
除了日志監控,還可以使用監控工具來實時監控Node.js應用的性能和健康狀況,例如Prometheus和Grafana。
Prometheus是一個開源的監控系統和時間序列數據庫。
你可以使用prom-client
庫將Node.js應用的指標暴露給Prometheus。
const promClient = require('prom-client');
const express = require('express');
const app = express();
const register = new promClient.Registry();
const httpRequestDurationMicroseconds = new promClient.Histogram({
name: 'http_request_duration_ms',
help: 'Duration of HTTP requests in ms',
labelNames: ['method', 'route', 'code'],
buckets: [0.10, 5, 15, 50, 100, 200, 300, 400, 500]
});
register.registerMetric(httpRequestDurationMicroseconds);
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
httpRequestDurationMicroseconds
.labels(req.method, req.route.path, res.statusCode)
.observe(duration);
});
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
promClient.collectDefaultMetrics({ register });
app.listen(9090); // Prometheus scrape endpoint
});
然后在Grafana中配置Prometheus數據源,并創建儀表板來監控應用的性能指標。
通過這些方法和工具,你可以有效地監控Node.js應用的運行狀態和性能,及時發現和解決問題。