1.0.0 • Published 6 months ago
nestjs-request-logger v1.0.0
NestJS Request Logger
A flexible request logging package for NestJS applications that uses Winston logger under the hood. It automatically logs all incoming requests and their responses with sensitive data masking capabilities. Works with both Express and Fastify!
Features
- Automatic request and response logging
- Compatible with both Express and Fastify
- Console and file logging support
- Automatic sensitive data masking (passwords, tokens, etc.)
- Request timing and response status tracking
- Configurable logging options
- TypeScript support
- Global module availability
Installation
With Express (default)
npm install nestjs-request-logger
With Fastify
npm install nestjs-request-logger @nestjs/platform-fastify
Dependencies
This package has the following peer dependencies:
{
"@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
"@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0"
}
And includes the following dependencies:
{
"winston": "^3.11.0"
}
Usage
Basic Setup with Express (default)
import { Module } from "@nestjs/common";
import { RequestLoggerModule } from "nestjs-request-logger";
@Module({
imports: [
RequestLoggerModule.forRoot({
console: true, // Enable console logging
file: true, // Enable file logging
filename: "logs/requests.log", // Log file path
level: "info", // Log level
}),
],
})
export class AppModule {}
Basic Setup with Fastify
import { NestFactory } from "@nestjs/core";
import {
FastifyAdapter,
NestFastifyApplication,
} from "@nestjs/platform-fastify";
import { AppModule } from "./app.module";
async function bootstrap() {
// Use Fastify adapter
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(3000);
}
bootstrap();
// app.module.ts (same as Express)
import { Module } from "@nestjs/common";
import { RequestLoggerModule } from "nestjs-request-logger";
@Module({
imports: [
RequestLoggerModule.forRoot({
console: true,
file: true,
filename: "logs/requests.log",
level: "info",
}),
],
})
export class AppModule {}
That's it! All requests to your application will now be automatically logged. The logger will record:
- Request details (method, path, IP)
- Request parameters (query, body, headers)
- Response status code
- Response time
- Timestamp
Customizing Sensitive Fields
You can customize which fields should be masked in the logs:
import { Injectable } from "@nestjs/common";
import { RequestLoggerService } from "nestjs-request-logger";
@Injectable()
export class AppService {
constructor(private readonly requestLogger: RequestLoggerService) {
// Add custom sensitive fields to be masked
requestLogger.setSensitiveFields([
"password",
"token",
"apiKey",
"secret",
"creditCard",
]);
}
}
Manual Logging (Optional)
While the middleware handles automatic logging, you can still use the logger service manually if needed:
import { Controller, Post, Req } from "@nestjs/common";
import { RequestLoggerService } from "nestjs-request-logger";
@Controller("example")
export class ExampleController {
constructor(private readonly requestLogger: RequestLoggerService) {}
@Post()
async create(@Req() request) {
// Manual logging if needed
this.requestLogger.logRequest({
ip: request.ip,
method: request.method,
path: request.path,
userId: request.user?.id, // Custom fields
params: request.params,
query: request.query,
body: request.body,
headers: request.headers,
timestamp: new Date(),
});
return { message: "Request logged!" };
}
}
Configuration Options
Option | Type | Default | Description |
---|---|---|---|
console | boolean | true | Enable console logging |
file | boolean | false | Enable file logging |
filename | string | 'logs/requests.log' | Log file path |
level | string | 'info' | Log level (error, warn, info, debug) |
Platform Support
- ✅ Express.js
- ✅ Fastify
- ✅ NestJS with Express
- ✅ NestJS with Fastify
License
MIT
1.0.0
6 months ago