All files / src/logger/node request-logger.ts

100% Statements 56/56
100% Branches 20/20
100% Functions 1/1
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159      1x 1x                                                                                                                                                                           1x 11x 2x 2x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x   11x 8x 8x   9x 9x 9x   9x 6x 6x   9x 5x 9x 2x 2x   9x 9x   9x 2x 2x 9x   9x 3x 3x 9x   9x 2x 2x 9x     9x 1x 1x 9x   9x 9x 9x   1x 1x 1x  
import type { IncomingMessage, ServerResponse } from 'node:http';
 
import type { Logger, LogLevel } from '../definition.ts';
import { OFF_LOGGER } from '../off-logger.ts';
import { withPrefix } from '../prefixed-logger.ts';
 
type RequestHandler = (req: IncomingMessage & { path?: string }, res: ServerResponse, next: () => void) => void;
 
export type RequestLoggerOptions = {
  /**
   * The prefix to apply to the logger.
   *
   * @default 'http'
   */
  readonly prefix?: string;
 
  /**
   * The level to use for when a request is received by the server.
   *
   * @default 'info'
   */
  readonly receivedLevel?: LogLevel;
 
  /**
   * The level to use for the close event, which is emitted when the underlying connection is closed, happening before
   * 'finish'.
   *
   * @default 'debug'
   */
  readonly closeLevel?: LogLevel;
 
  /**
   * The level to use for the finish event, which is emitted when the response has been sent to the client.
   *
   * @default 'info'
   */
  readonly finishLevel?: LogLevel;
 
  /**
   * The level to use for the end event, which may be emitted when the entire response has been sent to the client,
   * happening after 'finish'.
   *
   * @default 'debug'
   */
  readonly endLevel?: LogLevel;
 
  /**
   * The level to use for the error event, which may occur at any time during the event lifecycle and is emitted when
   * there's an error writing the response.
   *
   * @default 'error'
   */
  readonly errorLevel?: LogLevel;
};
 
/**
 * Creates a lightweight HTTP request logger middleware for Node runtimes.
 *
 * The handler uses Node's native `IncomingMessage` and `ServerResponse`, making it a drop-in logger for Express and
 * similar frameworks without requiring them as dependencies. Each request is tracked with a sequential identifier and
 * logs lifecycle events (`received`, `close`, `finish`, `end`, and `error`) along with execution time.
 *
 * Default log levels favour surfacing `received`/`finish` at `info` while keeping `close`/`end` at `debug` to reduce
 * noise when connections terminate normally. Adjust them through {@link RequestLoggerOptions} to match your logging
 * policy.
 *
 * @example Express integration
 *
 * ```ts
 * import express from 'express';
 * import { createConsoleLogLogger, requestLogger } from 'emitnlog/logger';
 *
 * const app = express();
 * const logger = createConsoleLogLogger('debug');
 * app.use(requestLogger(logger));
 * ```
 *
 * @example Custom prefix and levels
 *
 * ```ts
 * app.use(
 *   requestLogger(logger, { prefix: 'api', receivedLevel: 'debug', finishLevel: 'debug', errorLevel: 'fatal' }),
 * );
 * ```
 *
 * @param logger Logger instance used to emit request lifecycle messages.
 * @param options Optional configuration for the logger prefix and per-event log levels.
 * @returns A Node-style middleware (`(req, res, next) => void`) that can be registered with Express or compatible
 *   routers.
 */
export const requestLogger = (logger: Logger, options?: RequestLoggerOptions): RequestHandler => {
  if (logger === OFF_LOGGER) {
    return NO_OP_REQUEST_HANDLER;
  }
 
  const config = {
    ...{
      prefix: 'http',
      receivedLevel: 'info',
      closeLevel: 'debug',
      finishLevel: 'info',
      endLevel: 'debug',
      errorLevel: 'error',
    },
    ...options,
  } as const satisfies RequestLoggerOptions;
 
  let requestCount = 0;
 
  if (config.prefix) {
    logger = withPrefix(logger, config.prefix);
  }
 
  return (req, res, next): void => {
    const requestIndex = requestCount++;
    let label = `${requestIndex}`;
 
    if (req.method) {
      label += `|${req.method}`;
    }
 
    if (req.path) {
      label += `:${req.path}`;
    } else if (req.url) {
      label += `:${req.url}`;
    }
 
    logger.log(config.receivedLevel, () => `received ${label}`);
    const start = performance.now();
 
    res.on('close', () => {
      const duration = performance.now() - start;
      logger.log(config.closeLevel, () => `closed ${label} after ${duration}ms`);
    });
 
    res.on('finish', () => {
      const duration = performance.now() - start;
      logger.log(config.finishLevel, () => `finished ${label} in ${duration}ms`);
    });
 
    res.on('end', () => {
      const duration = performance.now() - start;
      logger.log(config.endLevel, () => `ended ${label} in ${duration}ms`);
    });
 
    // May occur at any time during the event lifecycle and is emitted when there's an error writing the response.
    res.on('error', (error) => {
      const duration = performance.now() - start;
      logger.args(error).log(config.errorLevel, () => `errored on ${label} after ${duration}ms (${error})`);
    });
 
    next();
  };
};
 
const NO_OP_REQUEST_HANDLER: RequestHandler = Object.freeze((_req, _res, next): void => {
  next();
});