Logger Documentation
This documentation explains the features and usage of Logger Module: Located at src/common/logger
Overview
Comprehensive logging system using Pino with file rotation, sensitive data redaction, and custom serializers for request/response logging. The system includes HTTP request/response logging, automatic sensitive data redaction, file rotation with compression, configurable log levels, pretty printing for development, route exclusion for health checks, request ID tracking across services, and memory usage and uptime debugging for non-production environments.
Related Documents
- Configuration Documentation - For logger configuration settings
- Environment Documentation - For logger environment variables
- Handling Error Documentation - For error logging integration
- Security and Middleware Documentation - For logger middleware and security features
- Security and Middleware Documentation - For request ID tracking across services
Table of Contents
- Overview
- Related Documents
- Configuration
- Usage
- Sensitive Data Redaction
- File Logging
- Auto Logging
- Console Output
- Request ID Tracking
Features:
- HTTP request/response logging with [Pino][ref-pino]
- Automatic sensitive data redaction
- File rotation with compression
- Configurable log levels
- Pretty printing for development
- Route exclusion for health checks
- Request ID tracking across services
- Memory usage and uptime debugging (non-production)
Configuration
Configuration is managed in src/configs/logger.config.ts. For environment variables, see Environment Documentation.
| Option | Description | Default |
|---|---|---|
enable | Enable/disable logging | false |
level | Minimum log level (error, warn, info, debug) | debug |
intoFile | Write logs to files | false |
filePath | Directory path for log files | /logs |
auto | Enable automatic HTTP request/response logging | false |
prettier | Enable pretty-printing in console | false |
Usage
Use NestJS Logger throughout the application:
export class UserService {
private readonly logger = new Logger(UserService.name);
async createUser(data: CreateUserDto) {
this.logger.log('Creating new user');
try {
const user = await this.userRepository.create(data);
this.logger.log(`User created: ${user.id}`);
return user;
} catch (error) {
this.logger.error(`Failed to create user: ${error.message}`, error.stack);
throw error;
}
}
}Log Levels
this.logger.error('Error message'); // error level
this.logger.warn('Warning message'); // warn level
this.logger.log('Info message'); // info level
this.logger.debug('Debug message'); // debug levelSensitive Data Redaction
The logger automatically redacts sensitive fields defined in src/common/logger/constants/logger.constant.ts:
export const LoggerSensitiveFields: string[] = [
'password',
'newPassword',
'oldPassword',
'token',
'authorization',
'bearer',
'secret',
'credential',
'jwt',
'x-api-key',
'apiKey',
'refreshToken',
'accessToken',
'sessionId',
'privateKey',
'secretKey',
'otp',
'recoveryCode',
// Add more fields as needed
];Sensitive fields in these paths are automatically replaced with [REDACTED]:
export const LoggerSensitivePaths = [
'req.body',
'req.headers',
'res.body',
'res.headers',
'request.body',
'request.headers',
'response.body',
'response.headers',
];Example
Request with sensitive data:
{
"username": "john",
"password": "secret123",
"apiKey": "abc-def-ghi"
}Logged as:
{
"username": "john",
"password": "[REDACTED]",
"apiKey": "[REDACTED]"
}Array Truncation:
Arrays longer than 10 items are automatically truncated:
{
"items": [
"item1",
"item2",
// ... first 10 items
{ "truncated": "...[TRUNCATED] - total length 50" }
]
}File Logging
Enable file logging by setting LOGGER_INTO_FILE=true. Logs are written to ./logs/api.log with automatic rotation:
- Size limit: 10MB per file
- Rotation: Daily or when size limit reached
- Compression: Gzip compression for rotated files
- Retention: Maximum 10 files, older than 7 days removed
File structure:
logs/
├── api.log # Current log file
├── api.log.1.gz # Rotated log (yesterday)
├── api.log.2.gz # Rotated log (2 days ago)
└── ...Auto Logging
Enable automatic HTTP request/response logging with LOGGER_AUTO=true.
Excluded Routes
Routes excluded from auto-logging (defined in logger.constant.ts):
export const LoggerExcludedRoutes: string[] = [
'/api/health*',
'/metrics*',
'/favicon.ico',
'/docs*',
'/',
];Console Output
Pretty Mode (LOGGER_PRETTIER=true)
Development-friendly colored output with structured formatting:
INFO [2025-12-01 15:18:54.496 +0700]: [ACKNestJs-Main] Logger Debug Level: debug
service: {
"name": "ACKNestJs",
"environment": "local",
"version": "8.0.0"
}
debug: {
"memory": {
"rss": 449,
"heapUsed": 182
},
"uptime": 2
}JSON Mode (LOGGER_PRETTIER=false)
Production-optimized structured JSON:
{
"level": 30,
"timestamp": 1764577182750,
"service": {
"name": "ACKNestJs",
"environment": "local",
"version": "8.0.0"
},
"context": "ACKNestJs-Main",
"debug": {
"memory": {
"rss": 413,
"heapUsed": 181
},
"uptime": 1
},
"msg": "Logger Debug Level: debug"
}Debug Information (Non-Production)
In non-production environments, additional debug info is included:
- memory.rss: Resident Set Size in MB
- memory.heapUsed: Heap used in MB
- uptime: Process uptime in seconds
Request ID Tracking
The logger extracts request IDs from these headers (in order):
export const LoggerRequestIdHeaders = [
'x-correlation-id',
'x-request-id',
];