UNPKG

express-smart-logger-pro

Version:

Professional Express logging middleware with advanced features and zero configuration

272 lines (225 loc) 7.88 kB
# Express Smart Logger Pro **Professional Express logging middleware that goes beyond basic logging.** ## What This Package Does This isn't just a logger - it's a **developer productivity tool** that automatically: - Logs every request with unique trace IDs - Links related requests together with correlation IDs - Tracks performance trends over time - Captures full error context automatically - Hides sensitive data with smart masking - Provides performance insights and monitoring - Adapts to development vs production environments ## Why This Package is Different **Other logging packages:** - Only do basic request/response logging - Require manual setup and configuration - Don't provide performance insights - Don't link related requests together - Don't capture error context automatically **This package:** - **Zero configuration** - Just plug it in - **Request correlation** - Automatically links related requests - **Performance insights** - Tracks trends, not just individual requests - **Error context** - Full debugging information automatically - **Production ready** - Enterprise-grade monitoring capabilities - **Developer workflow** - Perfect for debugging complex systems ## Quick Start ### Install ```bash npm install express-smart-logger-pro ``` ### Use ```javascript const express = require('express'); const logger = require('express-smart-logger-pro'); const app = express(); app.use(logger()); // That's it! app.get('/user', (req, res) => { res.json({ name: 'John', password: 'secret123' // Will be hidden automatically }); }); ``` ## All Features (Built-In, No Extra Setup) ### 🔍 **Core Logging (Always Active)** - **Trace ID** - Every request gets unique ID like `[TRACE-abc123]` - **Request Details** - Method, URL, status, duration - **Response Data** - What your API returns (with sensitive data hidden) - **Performance** - Request timing and slow request detection - **Environment** - Colored logs in dev, JSON in production ### 🚀 **Advanced Features (Always Active)** - **Request Correlation** - Automatically links related requests together - **Performance Insights** - Tracks performance trends over time - **Error Context** - Captures full request context when errors occur - **Smart Masking** - Hides passwords, tokens, secrets automatically ### 📊 **Performance Monitoring (Always Active)** - **Trend Tracking** - Average, Min, Max response times per endpoint - **Error Rates** - Track error counts per endpoint - **Performance Degradation** - Detect when endpoints slow down - **Historical Data** - Performance data over time ### 🛡️ **Security Features (Always Active)** - **Auto-Masking** - Hides sensitive fields automatically - **Smart Masking** - Uses asterisks (`********`) instead of generic text - **Default Protection** - Covers: password, token, secret, key, auth, authorization - **Custom Fields** - Add your own sensitive fields to hide ## Extra Features (Turn On When Needed) ```javascript // Basic usage - all advanced features work automatically app.use(logger()); // Enhanced usage - enable additional logging app.use(logger({ logBody: true, // Log incoming request data logHeaders: true, // Log user-agent and IP address logSize: true, // Log request/response sizes mask: ['creditCard', 'ssn'], // Hide additional sensitive fields slowThreshold: 2000, // Alert for requests slower than 2 seconds enableCorrelation: true, // Link related requests together enablePerformanceInsights: true, // Track performance trends over time enableErrorContext: true // Capture full error context })); ``` ## What You'll See ### Development (Colored logs ) ``` [TRACE-abc123] GET /user 200 (15ms) Correlation ID: def456 Request Size: 45 bytes User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 IP: 192.168.1.100 Request Body: { "email": "john@example.com", "password": "********" } Performance: Avg: 12ms, Min: 8ms, Max: 25ms Response Size: 89 bytes Response: { "name": "John", "password": "********" } ``` ### Production (JSON logs ) ```json { "traceId": "abc123", "correlationId": "def456", "timestamp": "2024-01-15T10:30:00.000Z", "method": "GET", "url": "/user", "status": 200, "duration": 15, "requestSize": 45, "responseSize": 89, "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0", "ip": "192.168.1.100", "requestBody": { "email": "john@example.com", "password": "********" }, "performance": { "avgTime": 12, "minTime": 8, "maxTime": 25, "count": 150, "errorCount": 2 }, "response": { "name": "John", "password": "********" } } ``` ## Advanced Developer Features ### Request Correlation Automatically links related requests together: ```javascript // All requests in a user session get the same correlation ID // Perfect for debugging complex workflows and user journeys // Track entire user sessions from login to logout ``` ### Performance Insights Tracks performance trends over time: ```javascript // Shows: Average, Min, Max response times per endpoint // Error rates and performance degradation alerts // Historical performance data for optimization // Identify which endpoints are slowing down over time ``` ### Enhanced Error Context When errors occur, automatically captures: ```javascript // Full request context (headers, body, trace ID) // Performance data at time of error // Correlation with other requests in the session // Perfect for debugging production issues ``` ### Performance Monitoring API Access performance data programmatically: ```javascript const logger = require('express-smart-logger'); // Get performance stats for all endpoints const stats = logger.getPerformanceStats(); console.log(stats); // Clear performance data logger.clearPerformanceStats(); // Get request correlation data const correlations = logger.getRequestCorrelation(); ``` ## What Gets Hidden Automatically These fields are automatically hidden with asterisks: - `password` → `********` - `token` → `****` - `secret` → `******` - `key` → `***` - `auth` → `****` - `authorization` → `************` ## Usage Examples ### Basic Usage ```javascript app.use(logger()); ``` ### With Request Body Logging ```javascript app.use(logger({ logBody: true, logHeaders: true })); ``` ### With Custom Masking ```javascript app.use(logger({ mask: ['creditCard', 'ssn', 'apiKey'] })); ``` ### Full Enterprise Setup ```javascript app.use(logger({ logBody: true, logHeaders: true, logSize: true, mask: ['creditCard', 'ssn', 'apiKey'], slowThreshold: 2000, enableCorrelation: true, enablePerformanceInsights: true, enableErrorContext: true })); ``` ## Environment Detection - **Development**: Colored console output with trace IDs and correlation IDs - **Production**: Structured JSON logs for log aggregation and monitoring Set `NODE_ENV=production` to enable production mode. ## Use Cases - **API Development** - Quick debugging with request correlation - **Production APIs** - Enterprise-grade monitoring and insights - **Microservices** - Track requests across service boundaries - **Complex Workflows** - Debug user journeys with correlation IDs - **Performance Optimization** - Identify slow endpoints and trends - **Error Investigation** - Full context for production debugging ## This Package Solves Real Problems - **"Why is my API slow?"** → Performance insights show trends over time - **"Which requests are related?"** → Correlation IDs link them automatically - **"What happened when this error occurred?"** → Full error context captured - **"How is my API performing?"** → Historical performance data available - **"Debug this user session"** → Correlation IDs track entire workflows ## License MIT