80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
import promClient from "prom-client";
|
||
|
||
const registry = new promClient.Registry();
|
||
registry.setDefaultLabels({ service: "iam" });
|
||
|
||
registry.registerMetric(
|
||
new promClient.Counter({
|
||
name: "iam_requests_total",
|
||
help: "Total number of iam requests",
|
||
labelNames: ["method", "endpoint", "status"],
|
||
}),
|
||
);
|
||
|
||
registry.registerMetric(
|
||
new promClient.Histogram({
|
||
name: "iam_request_duration_seconds",
|
||
help: "Iam request duration in seconds",
|
||
labelNames: ["method", "endpoint"],
|
||
buckets: [0.01, 0.05, 0.1, 0.3, 0.5, 1, 3, 5],
|
||
}),
|
||
);
|
||
|
||
// 自动收集 Node.js 进程级指标(CPU/内存/事件循环/GC等)
|
||
// 这些指标无需业务代码埋点,prom-client 自动采集
|
||
promClient.collectDefaultMetrics({ register: registry });
|
||
|
||
// Redis 权限缓存指标(I3 裁决:DB 驱动 + Redis 缓存可观测性)
|
||
registry.registerMetric(
|
||
new promClient.Counter({
|
||
name: "iam_permission_cache_hits_total",
|
||
help: "Total number of permission cache hits (Redis)",
|
||
}),
|
||
);
|
||
|
||
registry.registerMetric(
|
||
new promClient.Counter({
|
||
name: "iam_permission_cache_misses_total",
|
||
help: "Total number of permission cache misses (Redis)",
|
||
}),
|
||
);
|
||
|
||
registry.registerMetric(
|
||
new promClient.Counter({
|
||
name: "iam_permission_cache_invalidations_total",
|
||
help: "Total number of permission cache invalidations (Redis)",
|
||
labelNames: ["reason"],
|
||
}),
|
||
);
|
||
|
||
/**
|
||
* 缓存指标访问器:供 PermissionCacheService 使用.
|
||
* 避免在业务代码中直接操作 registry,统一通过此门面.
|
||
*/
|
||
export const cacheMetrics = {
|
||
recordHit(): void {
|
||
const metric = registry.getSingleMetric("iam_permission_cache_hits_total");
|
||
if (metric && "inc" in metric) {
|
||
(metric as promClient.Counter).inc();
|
||
}
|
||
},
|
||
recordMiss(): void {
|
||
const metric = registry.getSingleMetric(
|
||
"iam_permission_cache_misses_total",
|
||
);
|
||
if (metric && "inc" in metric) {
|
||
(metric as promClient.Counter).inc();
|
||
}
|
||
},
|
||
recordInvalidation(reason: string): void {
|
||
const metric = registry.getSingleMetric(
|
||
"iam_permission_cache_invalidations_total",
|
||
);
|
||
if (metric && "inc" in metric) {
|
||
(metric as promClient.Counter).inc({ reason });
|
||
}
|
||
},
|
||
};
|
||
|
||
export { registry as metricsRegistry };
|