2.0.1 โ€ข Published 5 months ago

@samofprog/nestjs-http-logger v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

๐Ÿ“ก HttpLoggerMiddleware

npm version License: MIT

HttpLoggerMiddleware is a powerful and configurable middleware for logging HTTP requests and responses in your NestJS application.
It provides detailed logs about incoming requests and completed responses, including HTTP method, URL, headers, response status, and processing duration.
Additional features include masking sensitive headers, ignoring specific paths, and supporting custom loggers.

โœจ Features

FeatureDescription
๐Ÿ“ฅ Detailed request and response loggingLogs HTTP method, URL, headers, status codes, and duration
๐Ÿ”’ Sensitive header maskingAllows masking sensitive headers like Authorization or Cookie
๐Ÿšซ Path ignoringIgnore logging on specific paths
๐Ÿ“ Custom log message formattingCustomize incoming and completed request log messages
๐Ÿ›  Custom logger supportUse your own LoggerService or fallback to NestJS global logger
โš ๏ธ Log level distinctionSuccessful responses logged with log, errors with error
โš™๏ธ Framework compatibilityWorks with both Express and Fastify

๐Ÿ“ฆ Installation

Install the package using npm or yarn:

npm install @samofprog/nestjs-http-logger
# or
yarn add @samofprog/nestjs-http-logger

๐Ÿš€ Usage

Use the middleware in your NestJS bootstrap file:

import { HttpLoggerMiddleware } from '@samofprog/nestjs-http-logger';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(HttpLoggerMiddleware.create());

  await app.listen(3000);
}
bootstrap();

โš™๏ธ Usage with Custom Configuration

You can customize the middleware behavior with options:

app.use(HttpLoggerMiddleware.create({
  ignorePaths: ['/health', '/metrics'],
  sensitiveHeaders: ['authorization', 'cookie'],
  sanitizeHeaders: (headers) => {
    const sanitized = { ...headers };
    ['authorization', 'cookie'].forEach(key => {
      if (sanitized[key]) sanitized[key] = '[REDACTED]';
    });
    return sanitized;
  },
  incomingRequestMessage: (details) =>
    `Incoming: ${details.method} ${details.url} โ†’ headers: ${JSON.stringify(details.headers)}`,
  completedRequestMessage: (details) =>
    `Completed: ${details.method} ${details.url} โ† status ${details.statusCode} in ${details.durationMs} ms`,
}));

๐Ÿ›  Options

OptionTypeDescriptionDefault
loggerLoggerServiceCustom logger implementing NestJS LoggerService interface.NestJS default logger
ignorePathsstring[]List of URL paths to ignore from logging.[]
sensitiveHeadersstring[]List of header names to mask in logs (case-insensitive).[]
sanitizeHeaders(headers: Record<string, any>) => Record<string, any>Function to transform headers before logging (e.g., to mask values).Identity function (no change)
incomingRequestMessage(details) => stringFunction returning the log message for incoming requests. Receives { method, url, headers }.Default formatted string
completedRequestMessage(details) => stringFunction returning the log message for completed requests. Receives { method, url, statusCode, durationMs }.Default formatted string

๐Ÿงฉ Examples

๐Ÿšซ Ignore paths and ๐Ÿ”’ mask sensitive headers

app.use(HttpLoggerMiddleware.create({
  ignorePaths: ['/health', '/metrics'],
  sensitiveHeaders: ['authorization', 'cookie'],
}));

๐Ÿงผ Custom sanitization of headers

app.use(HttpLoggerMiddleware.create({
  sanitizeHeaders: (headers) => {
    const sanitized = { ...headers };
    if (sanitized['authorization']) sanitized['authorization'] = '[TOKEN REDACTED]';
    if (sanitized['cookie']) sanitized['cookie'] = '[COOKIE REDACTED]';
    return sanitized;
  }
}));

๐Ÿงผ Custom sanitization of headers

import { Logger } from '@nestjs/common';

const customLogger = new Logger('MyCustomLogger');

app.use(HttpLoggerMiddleware.create({ logger: customLogger }));

๐Ÿ“„ License

This package is open-source and available under the MIT License.