From 0fff40f912259e2e9ea1cbec528767fce35336de Mon Sep 17 00:00:00 2001 From: Miodec Date: Fri, 23 Sep 2022 20:02:29 +0200 Subject: [PATCH] added country log test --- backend/src/api/routes/swagger.ts | 9 +++++++++ backend/src/utils/prometheus.ts | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/backend/src/api/routes/swagger.ts b/backend/src/api/routes/swagger.ts index 43e857d77..c1675f538 100644 --- a/backend/src/api/routes/swagger.ts +++ b/backend/src/api/routes/swagger.ts @@ -4,6 +4,7 @@ import swaggerStats from "swagger-stats"; import swaggerUi from "swagger-ui-express"; import publicSwaggerSpec from "../../documentation/public-swagger.json"; import internalSwaggerSpec from "../../documentation/internal-swagger.json"; +import { recordRequestCountry } from "../../utils/prometheus"; const SWAGGER_UI_OPTIONS = { customCss: ".swagger-ui .topbar { display: none } .try-out { display: none }", @@ -32,6 +33,14 @@ function addSwaggerMiddlewares(app: Application): void { swaggerUi.serve, swaggerUi.setup(publicSwaggerSpec, SWAGGER_UI_OPTIONS) ); + + app.use((req, res, next) => { + const country = req.headers["cf-ipcountry"] as string; + if (country) { + recordRequestCountry(country, req as MonkeyTypes.Request); + } + next(); + }); } export default addSwaggerMiddlewares; diff --git a/backend/src/utils/prometheus.ts b/backend/src/utils/prometheus.ts index 3669b3cb7..1e3c6d854 100644 --- a/backend/src/utils/prometheus.ts +++ b/backend/src/utils/prometheus.ts @@ -205,3 +205,25 @@ export function recordAuthTime( authTime.observe({ type, status, path: pathNoGet }, time); } + +const requestCountry = new Counter({ + name: "api_request_country", + help: "Country of request", + labelNames: ["path", "country"], +}); + +export function recordRequestCountry( + country: string, + req: MonkeyTypes.Request +): void { + const reqPath = req.baseUrl + req.route.path; + + let normalizedPath = "/"; + if (reqPath !== "/") { + normalizedPath = reqPath.endsWith("/") ? reqPath.slice(0, -1) : reqPath; + } + + const pathNoGet = normalizedPath.replace(/\?.*/, ""); + + requestCountry.inc({ path: pathNoGet, country }); +}