|
| 1 | +/*! |
| 2 | + * Copyright 2025 - Swiss Data Science Center (SDSC) |
| 3 | + * A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and |
| 4 | + * Eidgenössische Technische Hochschule Zürich (ETHZ). |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +import type { Express } from "express"; |
| 20 | +import type { PrometheusContentType, Registry } from "prom-client"; |
| 21 | + |
| 22 | +interface MetricsArgs { |
| 23 | + app: Express; |
| 24 | + metricsApp: Express; |
| 25 | +} |
| 26 | + |
| 27 | +export async function metrics({ |
| 28 | + app, |
| 29 | + metricsApp, |
| 30 | +}: MetricsArgs): Promise<Registry<PrometheusContentType>> { |
| 31 | + // Initialize metrics |
| 32 | + const promClient = await import("prom-client"); |
| 33 | + const promBundle = (await import("express-prom-bundle")).default; |
| 34 | + const register = new promClient.Registry(); |
| 35 | + |
| 36 | + // Collect default metrics |
| 37 | + promClient.collectDefaultMetrics({ register }); |
| 38 | + |
| 39 | + // Register the "prom-bundle" middleware |
| 40 | + app.use( |
| 41 | + promBundle({ |
| 42 | + autoregister: false, |
| 43 | + includeMethod: true, |
| 44 | + includeStatusCode: true, |
| 45 | + metricsApp, |
| 46 | + promRegistry: register, |
| 47 | + }) |
| 48 | + ); |
| 49 | + |
| 50 | + // Collect HTTP requests total (App only) |
| 51 | + const requestCounter = new promClient.Counter({ |
| 52 | + name: "http_requests_total", |
| 53 | + help: "Total number of HTTP requests.", |
| 54 | + labelNames: ["method", "status_code"], |
| 55 | + registers: [register], |
| 56 | + }); |
| 57 | + app.use(async (req, res, next) => { |
| 58 | + res.on("close", () => { |
| 59 | + requestCounter |
| 60 | + .labels({ |
| 61 | + method: req.method, |
| 62 | + status_code: res.statusCode, |
| 63 | + }) |
| 64 | + .inc(); |
| 65 | + }); |
| 66 | + next(); |
| 67 | + }); |
| 68 | + |
| 69 | + return register; |
| 70 | +} |
0 commit comments