-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (60 loc) · 2.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict'
const { Histogram, Summary } = require('prom-client')
const fp = require('fastify-plugin')
const defaultLabels = ['method', 'route', 'status_code']
const defaultIgnoreMethods = ['HEAD', 'OPTIONS', 'TRACE', 'CONNECT']
module.exports = fp(async function (fastify, opts) {
const getCustomLabels = opts.getCustomLabels || (() => ({}))
const customLabelNames = opts.customLabels || []
const labelNames = [...new Set([...defaultLabels, ...customLabelNames])]
const registers = [opts.registry]
const ignoreMethods = opts.ignoreMethods || defaultIgnoreMethods
const ignoreRoutes = opts.ignoreRoutes || []
const ignore = opts.ignore || (() => false)
function ignoreRoute (request) {
if (ignoreMethods.includes(request.method)) return true
const routePath = request.routeOptions.url ?? 'unknown'
if (ignoreRoutes.includes(routePath)) return true
return false
}
const summary = new Summary({
name: 'http_request_summary_seconds',
help: 'request duration in seconds summary',
labelNames,
registers,
...opts.summary,
})
const histogram = new Histogram({
name: 'http_request_duration_seconds',
help: 'request duration in seconds',
labelNames,
registers,
...opts.histogram,
})
const timers = new WeakMap()
fastify.addHook('onRequest', async (req) => {
if (ignoreRoute(req)) return
const summaryTimer = summary.startTimer()
const histogramTimer = histogram.startTimer()
timers.set(req, { summaryTimer, histogramTimer })
})
fastify.addHook('onResponse', async (req, reply) => {
if (ignoreRoute(req)) return
const requestTimers = timers.get(req)
if (!requestTimers) return
const { summaryTimer, histogramTimer } = requestTimers
timers.delete(req)
if (ignore(req, reply)) return
const routePath = req.routeOptions.url ?? 'unknown'
const labels = {
method: req.method,
route: routePath,
status_code: reply.statusCode,
...getCustomLabels(req, reply),
}
if (summaryTimer) summaryTimer(labels)
if (histogramTimer) histogramTimer(labels)
})
}, {
name: 'fastify-http-metrics'
})