@cemiar/logger
v1.0.2
Published
Cemiar package to handle logger in appinsight
Keywords
Readme
@cemiar/logger
A TypeScript logging package for Azure Application Insights with built-in sensitive data masking and operation correlation support.
Features
- 🔒 Automatic Sensitive Data Masking - Automatically masks email addresses and physical addresses in log messages
- 📊 Azure Application Insights Integration - Seamless integration with Azure Application Insights for centralized logging
- 🔗 Operation Correlation - Group related logs together using operation IDs for end-to-end transaction tracing
- 🎯 Multiple Severity Levels - Support for Info, Warning, Error, and Critical log levels
- 🖥️ Console Output - Optional console logging for development debugging
- 📦 Singleton Pattern - Thread-safe singleton instance for consistent logging across your application
Installation
npm install @cemiar/loggerRequirements
- Node.js >= 18.16.0
- npm >= 9.5.1
Quick Start
1. Configure the Logger
Before using the logger, you must configure it with your Application Insights connection string:
import { AppInsightsLogger } from '@cemiar/logger';
AppInsightsLogger.configure({
connectionString: 'YOUR_APPLICATION_INSIGHTS_CONNECTION_STRING',
sourceApp: 'my-app-name',
printOnConsole: true, // Optional: enables console output (default: false)
});2. Get the Logger Instance
const logger = AppInsightsLogger.getInstance();3. Start Logging
// Log information
logger.logInfo('User logged in successfully', { userId: '12345' });
// Log warnings
logger.logWarning('API rate limit approaching', { currentRate: 95 });
// Log exceptions
try {
// some code that might throw
} catch (error) {
logger.logException('Failed to process payment', error as Error, { orderId: 'ORD-123' });
}
// Log critical issues
logger.logCritical('Database connection lost', { server: 'db-primary' });Configuration Options
| Option | Type | Required | Default | Description |
| ------------------ | --------- | -------- | ------- | -------------------------------------------- |
| connectionString | string | Yes | - | Azure Application Insights connection string |
| sourceApp | string | Yes | - | Application name for identifying log sources |
| printOnConsole | boolean | No | false | Enable console output for debugging |
API Reference
AppInsightsLogger.configure(config: LoggerConfig)
Static method to configure the logger. Must be called before getInstance().
AppInsightsLogger.getInstance()
Returns the singleton logger instance. Throws an error if configure() has not been called.
AppInsightsLogger.resetInstance()
Resets the singleton instance. Useful for testing purposes.
Logging Methods
logInfo(message: string, data?: any)
Logs an informational message.
logWarning(message: string, data?: any)
Logs a warning message.
logException(message: string, error: Error, data?: any)
Logs an error/exception with stack trace.
logCritical(message: string, data?: any)
Logs a critical message.
Operation Correlation
withOperation<T>(operationId: string, fn: () => Promise<T>): Promise<T>
Wraps an async function with an operation context. All logs within this context will share the same operation ID, making it easy to trace related logs in Application Insights.
const operationId = `order-${orderId}-${Date.now()}`;
await logger.withOperation(operationId, async () => {
logger.logInfo('Starting order processing', { orderId });
// Process order...
await processPayment();
logger.logInfo('Order processed successfully', { orderId });
});Sensitive Data Masking
The logger automatically masks sensitive information in your log messages and data:
Email Addresses
[email protected] → jo****@example.comPhysical Addresses
123 Main Street, City → [REDACTED_ADDRESS]This helps ensure compliance with privacy regulations and prevents accidental exposure of PII (Personally Identifiable Information).
Concurrent Operations Example
The logger supports concurrent operations with proper correlation:
async function handleMultipleRequests() {
const operation1 = logger.withOperation('op-1', async () => {
logger.logInfo('Processing request 1');
await someAsyncWork();
logger.logInfo('Request 1 completed');
return 'result-1';
});
const operation2 = logger.withOperation('op-2', async () => {
logger.logInfo('Processing request 2');
await someOtherAsyncWork();
logger.logInfo('Request 2 completed');
return 'result-2';
});
const [result1, result2] = await Promise.all([operation1, operation2]);
}Each operation's logs will be grouped together in Application Insights, even when running concurrently.
Best Practices
- Configure Early - Call
AppInsightsLogger.configure()at application startup - Use Operation IDs - Wrap related operations with
withOperation()for better tracing - Include Context Data - Pass relevant data objects to help with debugging
- Appropriate Severity - Use the correct log level for each situation:
logInfo: Normal operations, audit trailslogWarning: Potential issues, degraded performancelogException: Errors that are handled but need attentionlogCritical: Severe issues requiring immediate attention
License
ISC
Author
Cemiar
