From 8dcbd5aec0d68cad9caa693edcd1db921e962eb7 Mon Sep 17 00:00:00 2001 From: Eric Mc Sween Date: Fri, 8 Jan 2021 14:53:29 -0500 Subject: [PATCH] Add support for the swagger-tools router The swagger-tools router puts the request path in the req.swagger.apiPath property. --- libraries/metrics/http.js | 46 +++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/libraries/metrics/http.js b/libraries/metrics/http.js index c0c387bfce..bca75b30a2 100644 --- a/libraries/metrics/http.js +++ b/libraries/metrics/http.js @@ -14,12 +14,12 @@ module.exports.monitor = logger => responseTime[0] * 1000 + responseTime[1] / 1000000 ) const requestSize = parseInt(req.headers['content-length'], 10) - if (req.route && req.route.path != null) { - const routePath = req.route.path - .toString() - .replace(/\//g, '_') - .replace(/:/g, '') - .slice(1) + const routePath = getRoutePath(req) + const remoteIp = getRemoteIp(req) + const reqUrl = req.originalUrl || req.url + const referrer = req.headers.referer || req.headers.referrer + + if (routePath != null) { Metrics.timing('http_request', responseTimeMs, null, { method: req.method, status_code: res.statusCode, @@ -33,12 +33,6 @@ module.exports.monitor = logger => }) } } - const remoteIp = - req.ip || - (req.socket && req.socket.socket && req.socket.socket.remoteAddress) || - (req.socket && req.socket.remoteAddress) - const reqUrl = req.originalUrl || req.url - const referrer = req.headers.referer || req.headers.referrer let info if (STACKDRIVER_LOGGING) { @@ -80,3 +74,31 @@ module.exports.monitor = logger => } next() } + +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 +} + +function getRemoteIp(req) { + if (req.ip) { + return req.ip + } + if (req.socket) { + if (req.socket.socket && req.socket.socket.remoteAddress) { + return req.socket.socket.remoteAddress + } else if (req.socket.remoteAddress) { + return req.socket.remoteAddress + } + } + return null +}