MCPcopy Create free account
hub / github.com/avoidwork/tenso / prometheus

Function prometheus

src/middleware/prometheus.js:9–73  ·  view source on GitHub ↗
(config)

Source from the content-addressed store, hash-verified

7 * @returns {Object} Object containing middleware function and metrics registry
8 */
9export function prometheus (config) {
10 // Create a Registry to register metrics
11 const register = new promClient.Registry();
12
13 // Add default metrics (process stats, etc.)
14 if (config.includeUp) {
15 promClient.collectDefaultMetrics({ register });
16 }
17
18 // Create histogram for request duration
19 const httpRequestDuration = new promClient.Histogram({
20 name: "http_request_duration_seconds",
21 help: "Duration of HTTP requests in seconds",
22 labelNames: ["method", "route", "status_code", ...Object.keys(config.customLabels || {})],
23 buckets: config.buckets || [0.001, 0.01, 0.1, 1, 2, 3, 5, 7, 10, 15, 20, 25, 30, 35, 40, 50, 70, 100, 200]
24 });
25
26 // Create counter for request count
27 const httpRequestsTotal = new promClient.Counter({
28 name: "http_requests_total",
29 help: "Total number of HTTP requests",
30 labelNames: ["method", "route", "status_code", ...Object.keys(config.customLabels || {})]
31 });
32
33 // Register metrics
34 register.registerMetric(httpRequestDuration);
35 register.registerMetric(httpRequestsTotal);
36
37 // Middleware function
38 const middleware = (req, res, next) => {
39 const startTime = Date.now();
40
41 // Store original end method
42 const originalEnd = res.end;
43
44 // Override end method to capture metrics
45 res.end = function (...args) {
46 const duration = (Date.now() - startTime) / 1000; // Convert to seconds
47 const route = req.route || req.url || "unknown";
48 const method = req.method || "unknown";
49 const statusCode = res.statusCode || 0;
50
51 // Build labels object
52 const labels = {
53 method: config.includeMethod ? method : "HTTP",
54 route: config.includePath ? route : "",
55 status_code: config.includeStatusCode ? statusCode.toString() : "",
56 ...config.customLabels
57 };
58
59 // Record metrics
60 httpRequestDuration.observe(labels, duration);
61 httpRequestsTotal.inc(labels);
62
63 // Call original end method
64 originalEnd.apply(this, args);
65 };
66

Callers 2

initMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected