forked from herrmannplatz/fastify-datadog
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·65 lines (49 loc) · 1.48 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
'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
}
let dynamicTags = tags
fastify.addHook('onRequest', async (req, reply) => {
req[startTimeSymbol] = now()
if (typeof tags === 'function') {
dynamicTags = tags(req)
}
})
fastify.addHook('onSend', async (req, reply) => {
const { context, statusCode } = reply
const statTags = [`route:${context.config.url}`].concat(dynamicTags)
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)
})
fastify.decorate('dogstatsd', dogstatsd)
}
module.exports = fp(fastifyDatadog, {
fastify: '3.x',
name: 'fastify-datadog'
})