@eqxjs/logger
v3.0.3
Published
A comprehensive logging library for NestJS applications that provides structured logging capabilities with masking, application insights integration, and summary logging features.
Keywords
Readme
@eqxjs/logger
A comprehensive logging library for NestJS applications that provides structured logging capabilities with masking, application insights integration, and summary logging features.
Installation
npm install @eqxjs/loggerDescription
This module exports various components related to logging functionality including:
- Data Transfer Objects (DTOs) for logger options, extra options, masking options, and summary log types
- Enumerations for masking and log levels
- Helper services for logging, masking, and application insights
- Logger DTOs and interfaces for log dependency metadata
- Services for flushing summary logs, logging, and summarizing logs
- Singleton logger services and their helpers
- The main logger module
These components provide a comprehensive logging framework that can be used to log, mask, and summarize logs in an application.
Usage
Basic Setup
import { Module } from '@nestjs/common';
import { LoggerModule } from '@eqxjs/logger';
@Module({
imports: [
LoggerModule.register({
app: {
name: 'MyApplication',
version: '1.0.0',
'component-name': 'MyComponent'
},
log: {
level: 'info',
detail: {
level: 'debug',
'enable-file-logging': true,
'log-file-properties': {
dirname: './logs',
filename: 'app-%DATE%.log',
'date-pattern': 'YYYY-MM-DD',
extension: '.log'
}
}
}
})
]
})
export class AppModule {}Using the Logger Service
import { Injectable } from '@nestjs/common';
import { CustomLoggerService } from '@eqxjs/logger';
@Injectable()
export class MyService {
constructor(private readonly logger: CustomLoggerService) {}
async someMethod() {
// Initialize logger
this.logger.init({
requestId: 'req-123',
userId: 'user-456'
});
// Log info with action data
this.logger.info(
{ action: 'USER_LOGIN', actionDescription: 'User login attempt', subAction: 'VALIDATE' },
{ username: 'john.doe', timestamp: new Date() }
);
// Log with masking sensitive data
this.logger.info(
{ action: 'PAYMENT_PROCESS', actionDescription: 'Processing payment', subAction: 'VALIDATE_CARD' },
{ cardNumber: '1234567890123456', amount: 100 },
[{ key: 'cardNumber', type: MaskingType.CREDIT_CARD }]
);
// Log errors
try {
// Some operation
} catch (error) {
this.logger.error(
{ action: 'DATABASE_OPERATION', actionDescription: 'Failed to save user', subAction: 'SAVE' },
{ userId: 'user-456' },
error.stack
);
}
}
}API Reference
Classes
LoggerModule
Main module class that provides configuration for the logging system.
Methods:
static register(options: object): DynamicModule- Registers the logger module with the provided configuration options
CustomLoggerService
Primary service class responsible for logging various levels of messages with optional data masking and metadata management.
Properties:
logDto: LogDto- The data transfer object for loggingisSetSummaryLogParameters: boolean- Indicates if summary log parameters are setsummaryLogParameters: SummaryParamsType- The parameters for summary loggingadditionalSummary: object- Additional summary information
Methods:
init(data: LogDto)- Initializes the logger service with provided log datagetSummaryLogAdditionalInfo()- Retrieves additional summary informationsetSummaryLogParameters(params: SummaryParamsType)- Sets summary log parametersgetIsSetSummaryLogParameters(): boolean- Checks if summary log parameters are setgetSummaryLogParameters(): SummaryParamsType- Retrieves summary log parameterssetDependencyMetadata(metadata: LogDependencyMetadata)- Sets dependency metadatagetLogDto(): LogDto- Retrieves the current log DTOupdate(key: string, value: any)- Updates log entry with specified key and valueinfo(actionData: ILoggerActionData, data: any, options?: MaskingOptionDto[])- Logs informational messagesdebug(actionData: ILoggerActionData, data: any, options?: MaskingOptionDto[])- Logs debug messageserror(actionData: ILoggerActionData, data: any, stack?: any, options?: MaskingOptionDto[])- Logs error messagessetSummaryLogErrorSource(param: ErrorSourceType)- Sets error source for summary logsetSummaryLogAdditionalInfo(key: string, value: any)- Sets additional info for summary logsetDetailLogAdditionalInfo(key: string, value: any)- Sets additional info for detailed log
CustomSummaryLoggerService
Service for handling summary logging functionality.
CustomSingletonLoggerService
Singleton pattern implementation of the logger service.
FlushSummaryLog
Service for flushing summary logs.
SingletonFlushSummaryLog
Singleton implementation for flushing summary logs.
LoggerHelperService
Helper service providing utility functions for logging operations.
SingletonLoggerHelperService
Singleton helper service for logging utilities.
MaskingService
Service for masking sensitive information in log data.
ApplicationInsightsService
Service for integrating with Microsoft Application Insights.
Data Transfer Objects (DTOs)
LogDto
Main data transfer object for log entries.
LoggerOptionDto
Configuration options for the logger.
Interfaces
ILoggerActionData
Interface defining the structure for logger action data:
action: string- The action being performedactionDescription: string- Description of the actionsubAction?: string- Optional sub-action
LogDependencyMetadata
Interface for log dependency metadata.
ErrorSourceType
Interface for error source information.
Enums
LogLevel
Enumeration of available log levels.
LogResultType
Enumeration of log result types.
LogSeverity
Enumeration of log severity levels.
MaskingType
Enumeration of masking types for sensitive data:
CREDIT_CARD- For credit card number maskingEMAIL- For email address maskingPHONE- For phone number maskingSSN- For social security number masking
Type Aliases
MaskingOptionDto
Type alias for masking configuration options.
LoggerExtraOptionDto
Type alias for additional logger options.
SummaryParamsType
Type alias for summary log parameters.
Functions
createNestDosLogger()
Creates a NestJS logger using the Winston logging library.
Returns: winston.Logger - A configured Winston logger instance
Variables
INTERNAL_LOGGER_OPTIONS
Internal configuration options for the logger.
INTERNAL_OS_NAME
Internal hostname of the operating system.
Features
Data Masking
The library supports automatic masking of sensitive data using predefined masking types:
// Mask credit card numbers
logger.info(
{ action: 'PAYMENT', actionDescription: 'Process payment' },
{ cardNumber: '1234567890123456' },
[{ key: 'cardNumber', type: MaskingType.CREDIT_CARD }]
);Application Insights Integration
Automatic integration with Microsoft Application Insights for advanced monitoring and telemetry.
Summary Logging
Support for summary logs that aggregate information across requests:
logger.setSummaryLogParameters({
transactionId: 'txn-123',
userId: 'user-456'
});
logger.setSummaryLogAdditionalInfo('totalProcessingTime', 1500);File Logging
Configurable file logging with daily rotation:
LoggerModule.register({
log: {
detail: {
'enable-file-logging': true,
'log-file-properties': {
dirname: './logs',
filename: 'app-%DATE%.log',
'date-pattern': 'YYYY-MM-DD',
extension: '.log'
}
}
}
});Singleton Pattern Support
Singleton implementations available for performance-critical scenarios where logger instances need to be shared across the application.
Configuration
The logger accepts the following configuration options:
{
app: {
name: string; // Application name
version: string; // Application version
'component-name': string; // Component name
},
log: {
level: string; // Log level (error, warn, info, debug)
detail?: {
level: string; // Detailed log level
'enable-file-logging': boolean; // Enable file logging
'log-file-properties': {
dirname: string; // Log file directory
filename: string; // Log filename pattern
'date-pattern': string; // Date pattern for rotation
extension: string; // File extension
}
}
}
}License
ISC
