UNPKG

@fran-834/gs-microservice-core

Version:

Core package for Node.js microservices by Galduria Software. Includes security, logging, validation, and error handling middlewares.

47 lines (46 loc) 1.56 kB
import morgan from "morgan"; import logger from "./logger.js"; /** * Morgan token to get the request ID. * Returns the request ID if it exists. */ morgan.token("id", function getId(req) { return req.id; }); morgan.token("browser", function getBrowser(req) { return req.context?.userAgent?.browser; }); morgan.token("os", function getOS(req) { return req.context?.userAgent?.os; }); morgan.token("device", function getDevice(req) { return req.context?.userAgent?.device; }); /** * Express middleware for HTTP logging with Morgan and Winston. * Logs request details in JSON format. */ const morganMiddleware = morgan(function (tokens, req, res) { return JSON.stringify({ requestId: tokens.id(req, res), client_ip: req.ip, method: tokens.method(req, res), url: tokens.url(req, res), status: Number.parseFloat(tokens.status(req, res) ?? "0"), content_length: tokens.res(req, res, "content-length"), response_time: Number.parseFloat(tokens["response-time"](req, res) ?? "0"), browser: tokens.browser(req, res), os: tokens.os(req, res), device: tokens.device(req, res), }); }, { skip: (req) => req.method === "OPTIONS" || req.url === "/health" || req.url.startsWith("/metrics"), stream: { // Configure Morgan to use our custom logger with the http severity write: (message) => { const data = JSON.parse(message); logger.info(`incoming-request`, data); }, }, }); export default morganMiddleware;