UNPKG

@rasla/express-logify

Version:

A beautiful, fast, and type-safe logging middleware for Express.js applications

52 lines (51 loc) 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.logger = logger; const logger_1 = require("./logger"); function logger(options = {}) { const loggerInstance = new logger_1.Logger(options); return (req, res, next) => { // Skip logging for specified paths if (options.skip?.includes(req.path)) { return next(); } const startTime = Date.now(); // Get IP address const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || ""; // Store the original end function const originalEnd = res.end; // Override end function to capture response res.end = function (chunk, encoding, cb) { const duration = Date.now() - startTime; loggerInstance.info({ method: req.method, path: req.path, statusCode: res.statusCode, duration, ip, message: `${req.method} ${req.path}`, }); if (typeof encoding === "function") { // @ts-ignore return originalEnd.call(this, chunk, encoding); } // @ts-ignore return originalEnd.call(this, chunk, encoding, cb); }; // Type assertion needed due to complex express types // Error handling res.on("error", (error) => { const duration = Date.now() - startTime; loggerInstance.error({ method: req.method, path: req.path, statusCode: res.statusCode, duration, ip, message: error.message, }); }); next(); }; }