UNPKG

rexuws

Version:

An express-like framework built on top of uWebsocket.js aims at simple codebase and high performance

57 lines (56 loc) 2.37 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.httpLogger = void 0; /* eslint-disable import/prefer-default-export */ const Logger_1 = __importDefault(require("../../../Logger")); const utils_1 = require("../../../utils"); // TODO add stream option /** * A simple HttpLogger inspired by morgan * * The message will be printed over info() method if the req.end() incl: send, json, sendStatus, sendFile (non streaming), gets executed. * * Warning: The peformance will be degraded when you use the module even when the logging level (in case you use the built-in Logger) is set to false * it'd be better if this middleware is used in development mode only * * Passing a custom console which must be extended from ILoggerProvider (@default console) * * If you want to use global application logging setting, use the code below * * @example * import rex, { getLoggerInstance, httpLogger } from 'rex' * const app = rex(); * app.use(httpLogger(getLoggerInstance())) * * @param opts */ const httpLogger = (_logger = console) => { let logger = _logger; if (logger instanceof Logger_1.default) { const baseOpts = logger.getOptions(); logger = new Logger_1.default(baseOpts, utils_1.colorConsoleNoTimestamp); } if (process.env.NODE_ENV === 'production') _logger.warn('You are using HttpLogger middleware in production mode which may decrease the overall performance!'); return (req, res, next) => { const { ip, method, url } = req; res.locals._startTimeAsLocaleString = new Date().toLocaleString(); res.locals._startTime = process.hrtime(); const { end } = res; const handleEnd = (...args) => { end.bind(res)(...args); setImmediate(() => { const timer = process.hrtime(res.locals._startTime); const timeInMs = `${((timer[0] * 1000000000 + timer[1]) / 1000000).toFixed(2)} ms`; logger.info(res.locals._startTimeAsLocaleString, ip, method.toUpperCase(), url, res._statusCode || 200, timeInMs); }); }; res.end = handleEnd; next(); }; }; exports.httpLogger = httpLogger;