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
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.