高级TypeScript应用监控:指标与告警
\n在现代开发中,监控已超越简单的“服务器是否存活”检查。对于在复杂分布式环境中运行的TypeScript应用,需要高级的可观测性系统。仅仅记录错误是不够的——必须收集自定义性能指标、配置智能告警并构建用于预测分析的仪表盘。本文将介绍如何使用现代工具和最佳实践实现专业的TypeScript应用监控。
\n\n1. 收集自定义性能指标
\n基础指标(CPU、内存)通常无法提供完整视图。对于TypeScript应用,业务指标和运行时指标至关重要。下面介绍如何使用prom-client库(Node.js的Prometheus客户端)配置自定义指标收集。
自定义指标类型
\n- \n
- Counter(计数器) — 用于计数事件(请求、错误)。 \n
- Gauge(仪表盘) — 用于可增减的值(活跃连接数)。 \n
- Histogram(直方图) — 用于值分布(响应时间)。 \n
- Summary(摘要) — 用于运行时百分位数。 \n
示例:在TypeScript中注册自定义指标
\nimport client from 'prom-client';\nimport express, { Request, Response } from 'express';\n\n// 创建指标注册表\nconst register = new client.Registry();\nclient.collectDefaultMetrics({ register });\n\n// 自定义错误计数器\nconst errorCounter = new client.Counter({\n name: 'app_errors_total',\n help: 'Total number of application errors',\n labelNames: ['type', 'code'],\n registers: [register],\n});\n\n// HTTP响应时间直方图\nconst httpRequestDuration = new client.Histogram({\n name: 'http_request_duration_seconds',\n help: 'Duration of HTTP requests in seconds',\n labelNames: ['method', 'route', 'status'],\n buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],\n registers: [register],\n});\n\n// 活跃用户仪表盘\nconst activeUsers = new client.Gauge({\n name: 'active_users_count',\n help: 'Number of currently active users',\n labelNames: ['user_type'],\n registers: [register],\n});\n\nconst app = express();\n\n// 请求时间测量中间件\napp.use((req: Request, res: Response, next) => {\n const end = httpRequestDuration.startTimer();\n res.on('finish', () => {\n end({ method: req.method, route: req.path, status: res.statusCode });\n });\n next();\n});\n\n// 指标端点\napp.get('/metrics', async (req: Request, res: Response) => {\n res.set('Content-Type', register.contentType);\n res.end(await register.metrics());\n});\n\n// 模拟错误\napp.get('/error', (req: Request, res: Response) => {\n errorCounter.inc({ type: 'validation', code: '400' });\n res.status(400).send('Bad Request');\n});\n\napp.listen(3000, () => console.log('Server on port 3000'));\n\n2. 集成Prometheus和Grafana
\n收集的指标需要导出和可视化。Prometheus将轮询我们的/metrics端点,而Grafana将在仪表盘上展示数据。
为TypeScript应用配置Prometheus
\n# prometheus.yml\nglobal:\n scrape_interval: 15s\nscrape_configs:\n - job_name: 'typescript-app'\n static_configs:\n - targets: ['localhost:3000']\n metrics_path: '/metrics'\n # 添加环境标签\n relabel_configs:\n - source_labels: [__address__]\n target_label: instance\n regex: '([^:]+):.*'\n replacement: '${1}'\n\n用于分析的进阶PromQL查询
\n- \n
rate(app_errors_total[5m])— 5分钟内的错误频率。 \nhistogram_quantile(0.95, rate(http_request_durati