Files
speckle-server/packages/server/observability/components/express/metrics/errorMetrics.ts
T
Iain Sproat 5e4a6c5635 fix(server/prometheus): ensure consistent Prometheus registry is used (#4106)
* fix(server/prometheus): ensure consistent Prometheus registry is used
- there was a conflicting dependency between Metrics initialization and Modules initialization; resolved by separating registry initialization from metrics initialization
- pass in the registry to prevent implicit dependency being broken
- when registering a metric, first attempt to remove any of existing metrics with same name to prevent errors
- to prevent sneaky uses of the implicit registry, replace default import with explicit import so it is clearer when prometheusClient.registry is used

* Add tests for registering metrics
2025-03-04 08:41:53 +00:00

28 lines
897 B
TypeScript

/* istanbul ignore file */
import type { Nullable } from '@speckle/shared'
import { Counter, type Registry } from 'prom-client'
import type { ErrorRequestHandler } from 'express'
let metricErrorCount: Nullable<Counter<'route'>> = null
export const errorMetricsMiddlewareFactory: (params: {
promRegisters: Registry[]
}) => ErrorRequestHandler = (params) => (err, req, res, next) => {
if (metricErrorCount === null) {
params.promRegisters.forEach((register) => {
register.removeSingleMetric('speckle_server_request_errors')
})
metricErrorCount = new Counter({
name: 'speckle_server_request_errors',
help: 'Number of requests that threw exceptions',
labelNames: ['route'],
registers: params.promRegisters
})
}
let route = 'unknown'
if (req.route && req.route.path) route = req.route.path
metricErrorCount.labels(route).inc()
next(err)
}