Error Logging in JavaScript

Log errors effectively

IntermediateError HandlingExample 6 of 10
error-logging.js
1// Method 1: Simple error logger
2class 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 };
10
11 console[level](JSON.stringify(logEntry, null, 2));
12 }
13}
14
15const logger = new ErrorLogger();
16try {
17 throw new Error('Test error');
18} catch (error) {
19 logger.log(error);
20}
21
22// Method 2: Structured logging
23class StructuredLogger {
24 log(error, metadata = {}) {
25 const logEntry = {
26 error: {
27 name: error.name,
28 message: error.message,
29 stack: error.stack
30 },
31 metadata: metadata,
32 timestamp: new Date().toISOString(),
33 environment: 'production'
34 };
35
36 console.error(JSON.stringify(logEntry));
37 }
38}
39
40// Method 3: Error levels
41const LogLevel = {
42 DEBUG: 'debug',
43 INFO: 'info',
44 WARN: 'warn',
45 ERROR: 'error',
46 FATAL: 'fatal'
47};
48
49class LeveledLogger {
50 log(error, level = LogLevel.ERROR) {
51 const entry = {
52 level: level,
53 error: error.message,
54 timestamp: Date.now()
55 };
56
57 if (level === LogLevel.ERROR || level === LogLevel.FATAL) {
58 entry.stack = error.stack;
59 }
60
61 console.log(JSON.stringify(entry));
62 }
63}
64
65// Method 4: Error aggregation
66class ErrorAggregator {
67 constructor() {
68 this.errors = new Map();
69 }
70
71 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 }
84
85 getSummary() {
86 return Array.from(this.errors.values());
87 }
88}
89
90const 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