2021-10-27 08:06:50 -04:00
|
|
|
const Metrics = require('./index')
|
2020-07-17 11:01:58 -04:00
|
|
|
|
2020-09-11 14:18:22 -04:00
|
|
|
module.exports.monitor = logger =>
|
2021-12-16 04:04:32 -05:00
|
|
|
function (req, res, next) {
|
2021-10-27 08:06:50 -04:00
|
|
|
const startTime = Date.now()
|
2020-09-11 14:18:22 -04:00
|
|
|
const { end } = res
|
2021-12-16 04:04:32 -05:00
|
|
|
res.end = function (...args) {
|
2021-10-27 08:06:50 -04:00
|
|
|
end.apply(this, args)
|
|
|
|
const responseTimeMs = Date.now() - startTime
|
2020-09-11 14:18:22 -04:00
|
|
|
const requestSize = parseInt(req.headers['content-length'], 10)
|
2021-01-08 14:53:29 -05:00
|
|
|
const routePath = getRoutePath(req)
|
|
|
|
const reqUrl = req.originalUrl || req.url
|
|
|
|
|
|
|
|
if (routePath != null) {
|
2020-09-11 14:18:22 -04:00
|
|
|
Metrics.timing('http_request', responseTimeMs, null, {
|
|
|
|
method: req.method,
|
|
|
|
status_code: res.statusCode,
|
2021-12-16 04:04:32 -05:00
|
|
|
path: routePath,
|
2020-09-11 14:18:22 -04:00
|
|
|
})
|
|
|
|
if (requestSize) {
|
|
|
|
Metrics.summary('http_request_size_bytes', requestSize, {
|
|
|
|
method: req.method,
|
|
|
|
status_code: res.statusCode,
|
2021-12-16 04:04:32 -05:00
|
|
|
path: routePath,
|
2020-09-11 14:18:22 -04:00
|
|
|
})
|
2020-07-17 11:01:58 -04:00
|
|
|
}
|
2020-09-11 14:18:22 -04:00
|
|
|
}
|
2021-10-27 08:06:50 -04:00
|
|
|
logger.info({ req, res, responseTimeMs }, '%s %s', req.method, reqUrl)
|
2020-09-11 14:18:22 -04:00
|
|
|
}
|
2021-01-08 14:41:50 -05:00
|
|
|
next()
|
2020-09-11 14:18:22 -04:00
|
|
|
}
|
2021-01-08 14:53:29 -05:00
|
|
|
|
|
|
|
function getRoutePath(req) {
|
|
|
|
if (req.route && req.route.path != null) {
|
|
|
|
return req.route.path
|
|
|
|
.toString()
|
|
|
|
.replace(/\//g, '_')
|
|
|
|
.replace(/:/g, '')
|
|
|
|
.slice(1)
|
|
|
|
}
|
|
|
|
if (req.swagger && req.swagger.apiPath != null) {
|
|
|
|
return req.swagger.apiPath
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|