From b2f4904b170f5d50260e6819a62b65c00f38b7f2 Mon Sep 17 00:00:00 2001 From: Phillip Thelen Date: Mon, 18 Nov 2024 15:51:44 +0100 Subject: [PATCH] log slow requests to loggly --- config.json.example | 3 ++- website/server/middlewares/index.js | 6 ++++++ .../server/middlewares/requestLogHandler.js | 18 ++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/config.json.example b/config.json.example index 9a50e86a222..d81f1b9ad9b 100644 --- a/config.json.example +++ b/config.json.example @@ -93,5 +93,6 @@ "TRUSTED_DOMAINS": "localhost,https://habitica.com", "TIME_TRAVEL_ENABLED": "false", "DEBUG_ENABLED": "false", - "CONTENT_SWITCHOVER_TIME_OFFSET": 8 + "CONTENT_SWITCHOVER_TIME_OFFSET": 8, + "SLOW_REQUEST_THRESHOLD": 1000 } diff --git a/website/server/middlewares/index.js b/website/server/middlewares/index.js index 1fef88f0543..e43e38ba008 100644 --- a/website/server/middlewares/index.js +++ b/website/server/middlewares/index.js @@ -33,12 +33,14 @@ import { } from './language'; import { logRequestData, + logSlowRequests, } from './requestLogHandler'; const IS_PROD = nconf.get('IS_PROD'); const DISABLE_LOGGING = nconf.get('DISABLE_REQUEST_LOGGING') === 'true'; const ENABLE_HTTP_AUTH = nconf.get('SITE_HTTP_AUTH_ENABLED') === 'true'; const LOG_REQUESTS_EXCESSIVE_MODE = nconf.get('LOG_REQUESTS_EXCESSIVE_MODE') === 'true'; +const SLOW_REQUEST_THRESHOLD = nconf.get('SLOW_REQUEST_THRESHOLD'); // const PUBLIC_DIR = path.join(__dirname, '/../../client'); const SESSION_SECRET = nconf.get('SESSION_SECRET'); @@ -51,6 +53,10 @@ export default function attachMiddlewares (app, server) { app.use(logRequestData); } + if (SLOW_REQUEST_THRESHOLD > 0) { + app.use(logSlowRequests); + } + if (ENABLE_CLUSTER) { app.use(domainMiddleware(server, mongoose)); } diff --git a/website/server/middlewares/requestLogHandler.js b/website/server/middlewares/requestLogHandler.js index 7191e116c0f..c398441103f 100644 --- a/website/server/middlewares/requestLogHandler.js +++ b/website/server/middlewares/requestLogHandler.js @@ -1,7 +1,10 @@ +import nconf from 'nconf'; import { v4 as uuid } from 'uuid'; import omit from 'lodash/omit'; import logger from '../libs/logger'; +const SLOW_REQUEST_THRESHOLD = nconf.get('SLOW_REQUEST_THRESHOLD'); + function buildBaseLogData (req) { return { requestId: req.requestIdentifier, @@ -35,3 +38,18 @@ export const logRequestData = (req, res, next) => { }); next(); }; + +export const logSlowRequests = (req, res, next) => { + req.requestStartTime = Date.now(); + req.on('close', () => { + const requestTime = Date.now() - req.requestStartTime; + if (requestTime > SLOW_REQUEST_THRESHOLD) { + const data = buildBaseLogData(req); + data.duration = requestTime; + data.endTime = Date.now(); + data.statusCode = res.statusCode; + logger.error(Error('Slow request'), data); + } + }); + next(); +};