From 6f0fe5ac5dbceeab9403777fb4a723072ef6a84e Mon Sep 17 00:00:00 2001 From: Myrotvorets Date: Wed, 20 Mar 2024 20:51:11 +0200 Subject: [PATCH] Refactoring --- package-lock.json | 14 +++++++++++-- package.json | 3 +-- src/middleware/duration.mts | 42 ------------------------------------- src/middleware/logger.mts | 26 ----------------------- src/server.mts | 21 ++++++++++++++----- 5 files changed, 29 insertions(+), 77 deletions(-) delete mode 100644 src/middleware/duration.mts delete mode 100644 src/middleware/logger.mts diff --git a/package-lock.json b/package-lock.json index 3ef22132..69e93971 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,14 +12,13 @@ "@cloudnative/health-connect": "^2.1.0", "@myrotvorets/express-async-middleware-wrapper": "^2.2.0", "@myrotvorets/express-microservice-middlewares": "^3.1.0", + "@myrotvorets/express-otel-middlewares": "^1.1.0", "@myrotvorets/express-request-logger": "^1.2.1", "@myrotvorets/oav-installer": "^5.0.0", "@myrotvorets/opentelemetry-configurator": "^7.6.0", "@myrotvorets/opentelemetry-plugin-knex": "^0.31.0", "@myrotvorets/otel-utils": "^1.2.0", "@opentelemetry/api": "^1.8.0", - "@opentelemetry/core": "^1.22.0", - "@opentelemetry/semantic-conventions": "^1.22.0", "awilix": "^10.0.1", "envalid": "^8.0.0", "express": "^4.18.3", @@ -516,6 +515,17 @@ "express-openapi-validator": "^3.0.0 || ^4.0.0 || ^5.0.0" } }, + "node_modules/@myrotvorets/express-otel-middlewares": { + "version": "1.1.0", + "resolved": "https://npm.pkg.github.com/download/@myrotvorets/express-otel-middlewares/1.1.0/acb8cdb17ee37df4ebe0d85e9c93cea046320bcb", + "integrity": "sha512-5VZi/+pekTno7nHXTQNx58i5sUa8C0EiiCE6wPpyPQf0FnzhXkDLbmOafTSaiE0OkRLaxKUjxbeukGQ2zT0VDQ==", + "peerDependencies": { + "@myrotvorets/express-request-logger": "^1.2.1", + "@opentelemetry/api": "^1.8.0", + "@opentelemetry/core": "^1.22.0", + "@opentelemetry/semantic-conventions": "^1.22.0" + } + }, "node_modules/@myrotvorets/express-request-logger": { "version": "1.2.1", "resolved": "https://npm.pkg.github.com/download/@myrotvorets/express-request-logger/1.2.1/7e0bc622b48db997ef1a202813cf89fe6cdb5020", diff --git a/package.json b/package.json index eb12039f..2278da15 100644 --- a/package.json +++ b/package.json @@ -26,14 +26,13 @@ "@cloudnative/health-connect": "^2.1.0", "@myrotvorets/express-async-middleware-wrapper": "^2.2.0", "@myrotvorets/express-microservice-middlewares": "^3.1.0", + "@myrotvorets/express-otel-middlewares": "^1.1.0", "@myrotvorets/express-request-logger": "^1.2.1", "@myrotvorets/oav-installer": "^5.0.0", "@myrotvorets/opentelemetry-configurator": "^7.6.0", "@myrotvorets/opentelemetry-plugin-knex": "^0.31.0", "@myrotvorets/otel-utils": "^1.2.0", "@opentelemetry/api": "^1.8.0", - "@opentelemetry/core": "^1.22.0", - "@opentelemetry/semantic-conventions": "^1.22.0", "awilix": "^10.0.1", "envalid": "^8.0.0", "express": "^4.18.3", diff --git a/src/middleware/duration.mts b/src/middleware/duration.mts deleted file mode 100644 index 708e4ab3..00000000 --- a/src/middleware/duration.mts +++ /dev/null @@ -1,42 +0,0 @@ -import type { RequestHandler } from 'express'; -import { hrTime, hrTimeDuration, hrTimeToMilliseconds } from '@opentelemetry/core'; -import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; -import type { OpenApiRequest } from '@myrotvorets/oav-installer'; -import { requestDurationHistogram } from '../lib/metrics.mjs'; - -export const requestDurationMiddleware: RequestHandler = (req, res, next): void => { - const start = hrTime(); - const recordDurarion = (): void => { - res.removeListener('error', recordDurarion); - res.removeListener('finish', recordDurarion); - const end = hrTime(); - const duration = hrTimeDuration(start, end); - - let route: string | undefined; - if ('openapi' in req && req.openapi) { - const r = req as OpenApiRequest; - /* c8 ignore next */ - route = r.openapi!.openApiRoute || r.openapi!.expressRoute; - } - - /* c8 ignore start */ - if (!route && req.route) { - route = (req.route as Record<'path', string>).path; - } - - if (!route) { - route = ''; - } - /* c8 ignore stop */ - - requestDurationHistogram.record(hrTimeToMilliseconds(duration), { - [SemanticAttributes.HTTP_METHOD]: req.method, - [SemanticAttributes.HTTP_ROUTE]: route, - [SemanticAttributes.HTTP_STATUS_CODE]: res.statusCode, - }); - }; - - res.prependOnceListener('error', recordDurarion); - res.prependOnceListener('finish', recordDurarion); - next(); -}; diff --git a/src/middleware/logger.mts b/src/middleware/logger.mts deleted file mode 100644 index 0c223477..00000000 --- a/src/middleware/logger.mts +++ /dev/null @@ -1,26 +0,0 @@ -/* c8 ignore start */ -import { requestLogger } from '@myrotvorets/express-request-logger'; -import type { NextFunction, Request, Response } from 'express'; -import type { LocalsWithContainer } from '../lib/container.mjs'; - -export const loggerMiddleware = - process.env['NODE_ENV'] !== 'test' - ? requestLogger({ - format: '[dzhura] :remote-addr :method :url :status :res[content-length] :date[iso] :total-time', - beforeLogHook: (err, _req, res, line, tokens): string => { - const { status } = tokens; - const message = `Status: ${status} len: ${tokens['res[content-length]']} time: ${tokens['total-time']}`; - const logger = res.locals.container.resolve('logger'); - if (+(status ?? '') >= 500 || err) { - logger.error(message); - } else if (+(status ?? '') >= 400) { - logger.warning(message); - } else { - logger.info(message); - } - - return line; - }, - }) - : (_req: Request, _res: Response, next: NextFunction): void => next(); -/* c8 ignore stop */ diff --git a/src/server.mts b/src/server.mts index c821b06b..e328e8f4 100644 --- a/src/server.mts +++ b/src/server.mts @@ -1,16 +1,23 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import express, { type Express } from 'express'; +import express, { type Express, type Request, type Response } from 'express'; import { installOpenApiValidator } from '@myrotvorets/oav-installer'; import { errorMiddleware, notFoundMiddleware } from '@myrotvorets/express-microservice-middlewares'; import { createServer, getTracer, recordErrorToSpan } from '@myrotvorets/otel-utils'; +import { + LoggerFromRequestFunction, + requestDurationMiddleware, + requestLoggerMiddleware, +} from '@myrotvorets/express-otel-middlewares'; -import { initializeContainer, scopedContainerMiddleware } from './lib/container.mjs'; -import { requestDurationMiddleware } from './middleware/duration.mjs'; -import { loggerMiddleware } from './middleware/logger.mjs'; +import { LocalsWithContainer, initializeContainer, scopedContainerMiddleware } from './lib/container.mjs'; import { searchController } from './controllers/search.mjs'; import { monitoringController } from './controllers/monitoring.mjs'; +import { requestDurationHistogram } from './lib/metrics.mjs'; + +const loggerFromRequest: LoggerFromRequestFunction = (req: Request) => + (req.res as Response | undefined)?.locals.container.resolve('logger'); export function configureApp(app: Express): ReturnType { return getTracer().startActiveSpan('configureApp', (span): ReturnType => { @@ -20,7 +27,11 @@ export function configureApp(app: Express): ReturnType