-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
executable file
·59 lines (44 loc) · 1.33 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
'use strict'
const fp = require('fastify-plugin')
const startTimeSymbol = Symbol('startTime')
async function fastifyDatadog (fastify, options = {}) {
const {
dogstatsd,
stat = 'node.fastify.router',
tags = [],
method = false,
path = false,
responseCode = false
} = options
if (dogstatsd == null) {
throw new Error('Missing dogstatsd option.')
}
const now = () => {
const [seconds, nanoseconds] = process.hrtime()
return seconds * 1e3 + nanoseconds / 1e6
}
fastify.addHook('onRequest', async (req, reply) => {
req[startTimeSymbol] = now()
})
fastify.addHook('onSend', async (req, reply) => {
const { statusCode } = reply
const statTags = [`route:${req.routeOptions.config.url}`, ...tags]
if (method) {
statTags.push(`method:${req.method.toLowerCase()}`)
}
if (path) {
statTags.push(`path:${req.url}`)
}
if (responseCode) {
statTags.push(`response_code:${statusCode}`)
dogstatsd.increment(`${stat}.response_code.${statusCode}`, 1, statTags)
dogstatsd.increment(`${stat}.response_code.all`, 1, statTags)
}
const resposeTime = now() - req[startTimeSymbol]
dogstatsd.histogram(`${stat}.response_time`, resposeTime, 1, statTags)
})
}
module.exports = fp(fastifyDatadog, {
fastify: '4.x',
name: 'fastify-datadog'
})