Error Logging in JavaScript
Log errors effectively
IntermediateError HandlingExample 6 of 10
error-logging.js
1// Method 1: Simple error logger2class ErrorLogger {3 log(error, level = 'error') {4 const logEntry = {5 level: level,6 message: error.message,7 stack: error.stack,8 timestamp: new Date().toISOString()9 };1011 console[level](JSON.stringify(logEntry, null, 2));12 }13}1415const logger = new ErrorLogger();16try {17 throw new Error('Test error');18} catch (error) {19 logger.log(error);20}2122// Method 2: Structured logging23class StructuredLogger {24 log(error, metadata = {}) {25 const logEntry = {26 error: {27 name: error.name,28 message: error.message,29 stack: error.stack30 },31 metadata: metadata,32 timestamp: new Date().toISOString(),33 environment: 'production'34 };3536 console.error(JSON.stringify(logEntry));37 }38}3940// Method 3: Error levels41const LogLevel = {42 DEBUG: 'debug',43 INFO: 'info',44 WARN: 'warn',45 ERROR: 'error',46 FATAL: 'fatal'47};4849class LeveledLogger {50 log(error, level = LogLevel.ERROR) {51 const entry = {52 level: level,53 error: error.message,54 timestamp: Date.now()55 };5657 if (level === LogLevel.ERROR || level === LogLevel.FATAL) {58 entry.stack = error.stack;59 }6061 console.log(JSON.stringify(entry));62 }63}6465// Method 4: Error aggregation66class ErrorAggregator {67 constructor() {68 this.errors = new Map();69 }7071 log(error) {72 const key = error.message;73 if (this.errors.has(key)) {74 this.errors.get(key).count++;75 } else {76 this.errors.set(key, {77 message: error.message,78 count: 1,79 firstSeen: Date.now(),80 lastSeen: Date.now()81 });82 }83 }8485 getSummary() {86 return Array.from(this.errors.values());87 }88}8990const aggregator = new ErrorAggregator();91aggregator.log(new Error('Network error'));92aggregator.log(new Error('Network error'));93console.log('Summary:', aggregator.getSummary());
Output
{
"level": "error",
"message": "Test error",
"stack": "Error: Test error\n at ...",
"timestamp": "2024-01-15T10:30:45.123Z"
}
Summary: [{ message: "Network error", count: 2, firstSeen: 1234567890, lastSeen: 1234567891 }]What's going on
Error logging tracks and analyzes errors.
Logging Methods
Simple logging
Structured logging
Leveled logging
Aggregation
Log Levels
DEBUG: Development
INFO: Information
WARN: Warnings
ERROR: Errors
FATAL: Critical
Structured Logs
JSON format
Include metadata
Timestamps
Stack traces
Error Aggregation
Group similar errors
Count occurrences
Track frequency
Identify patterns
Best Practices
Use structured logs
Include context
Set appropriate levels
Aggregate for analysis