Skip to content

samofprog/nestjs-http-logger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“‘ 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

Method 1: Using the Helper Function (Recommended)

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.

About

A NestJS middleware for logging HTTP requests

Resources

License

Stars

Watchers

Forks

Packages

No packages published