跳到主要内容

Prometheus-Grafana

2024年06月17日
柏拉文
越努力,越幸运

一、认识


Prometheus 是一套成熟且流行的系统和服务监控系统,它几乎满足了监控的所有能力。Prometheus 是一种用于监控和警报的开源系统,可用于对数据中心和云环境中的生产服务进行监控和警告。Prometheus 可用于服务发现、时间序列数据存储、实时查询和警报聚合,因此是一个强大的工具集合。 使用 Prometheus 可以快速和有效地收集它提供的标准指标,轻松实现实时性能监控及报警机制的设置。

PrometheusNode.js 服务监控支持多种使用场景,包括:性能监控,日志文件监控,内存分析以及运行时追踪。使用 Prometheus,可以轻松跟踪 Node.js 服务的URL访问、HTTP头和客户端请求信息,也可以针对每个实例查看服务指标,并将其写入 Prometheus 缓存。

Grafana 是一个数据可视化工具,它可以使用 Prometheus 的指标数据,并可视化出来,用于 Node.js 服务的监控。

Grafana 是图形化展示,有强大、灵活的仪表盘体系。我们会把基于Prometheus收集的数据作为数据源导入到Grafana, 搭建 Node.js 服务监控系统,实现实时性能监控,并显示可视化图形。

二、搭建 Node


2.1 metrics.js

import { register,Summary, Counter,  collectDefaultMetrics } from 'prom-client';

collectDefaultMetrics({ register });

export const curlResponseTime = new Summary({
name: 'curl_http_response_time_ms',
help: 'ms to curl a request',
labelNames: ['method', 'path', 'httpStatus', 'code'],
});

export const curlRequestTotal = new Counter({
name: 'curl_http_request_total',
help: 'number of curl requests to a route',
labelNames: ['method', 'path', 'httpStatus', 'code'],
});

export const responseTime = new Summary({
name: 'http_response_time_ms',
help: 'ms to handle a request',
labelNames: ['method', 'path', 'httpStatus', 'code'],
});

export const requestTotal = new Counter({
name: 'http_request_total',
help: 'number of requests to a route',
labelNames: ['method', 'path', 'httpStatus', 'code'],
});

export { register };

2.2 index.js

import Koa from 'koa';
import KoaRouter from 'koa-router';
import { register } from "./metrics.js";

const app = new Koa();
const router = new KoaRouter({ prefix: '' });

router.get('/', async ctx => {
ctx.body = 'Hello World';
});

router.get('/metrics', async ctx => {
ctx.headers['content-type'] = register.contentType;
ctx.body = await register.metrics();
});

app.use(router.routes());
app.listen(4000, () => {
console.log('Server is running at http://localhost:4000');
});

三、Grafana 搭建


请前往 Grafana 搭建

四、Prometheus 搭建


请前往 Prometheus 搭建

参考资料


基于Prometheus的node服务监控

Node.js 服务保姆级监控:带你体验 Prometheus 的魅力