JSPM

@samofprog/nestjs-http-logger

3.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 9
  • Score
    100M100P100Q9698F
  • License MIT

A NestJS middleware for logging HTTP requests

Package Exports

  • @samofprog/nestjs-http-logger
  • @samofprog/nestjs-http-logger/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@samofprog/nestjs-http-logger) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

๐Ÿ“ก NestJS HTTP Logger

npm version License: MIT

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

Feature Description
๐Ÿ“ฅ Detailed request and response logging Logs HTTP method, URL, headers, status codes, and duration
๐Ÿ”’ Sensitive header masking Allows masking sensitive headers like Authorization or Cookie
๐Ÿšซ Path ignoring Ignore logging on specific paths
๐Ÿ“ Custom log message formatting Customize incoming and completed request log messages
๐Ÿ›  Custom logger support Use your own LoggerService or fallback to NestJS global logger
โš ๏ธ Log level distinction Successful responses logged with log, errors with error
โš™๏ธ Framework compatibility Works with both Express and Fastify
๐ŸŽ›๏ธ Configurable logging levels Control what data to log: headers, request body, response data

๐Ÿ“ฆ Installation

Install the package using npm or yarn:

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

๐Ÿš€ Usage

Use the helper function in your NestJS bootstrap file:

import { createHttpLoggerMiddleware } 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(createHttpLoggerMiddleware());

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

Method 2: Using Providers (Advanced)

For more advanced use cases with dependency injection:

import { createHttpLoggerProviders } from '@samofprog/nestjs-http-logger';

@Module({
  providers: [
    ...createHttpLoggerProviders({
      ignorePaths: ['/health'],
      logHeaders: true,
    }),
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(HttpLoggerMiddleware).forRoutes('*');
  }
}

โš™๏ธ Usage with Custom Configuration

You can customize the middleware behavior with options:

import { createHttpLoggerMiddleware } from '@samofprog/nestjs-http-logger';

app.use(createHttpLoggerMiddleware({
  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

Option Type Description Default
logger LoggerService Custom logger implementing NestJS LoggerService interface. NestJS default logger
ignorePaths string[] List of URL paths to ignore from logging. []
sensitiveHeaders string[] List of header names to mask in logs (case-insensitive). ['authorization', 'cookie', 'set-cookie', 'x-api-key']
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) => string Function returning the log message for incoming requests. Receives { method, url, headers, body }. Default formatted string
completedRequestMessage (details) => string Function returning the log message for completed requests. Receives { method, url, statusCode, durationMs, responseData }. Default formatted string
logHeaders boolean Whether to include headers in the log messages. false
logRequestBody boolean Whether to include request body in the log messages. false
logResponseData boolean Whether to include response data in the log messages. false

๐Ÿงฉ Examples

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

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

๐Ÿงผ Custom sanitization of headers

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

๐ŸŽ›๏ธ Configure logging levels

app.use(createHttpLoggerMiddleware({
  logHeaders: true,        // Include headers in logs (default: false)
  logRequestBody: true,    // Include request body in logs (default: false)
  logResponseData: true,   // Include response data in logs (default: false)
}));

๐Ÿ›  Custom logger

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

const customLogger = new Logger('MyCustomLogger');

app.use(createHttpLoggerMiddleware({ logger: customLogger }));

๐Ÿ”ง Default Sensitive Headers

By default, the following headers are automatically masked:

const DEFAULT_SENSITIVE_HEADERS = [
  'authorization',
  'cookie', 
  'set-cookie',
  'x-api-key'
];

๐Ÿ“„ License

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