Error Logging
Log errors effectively
IntermediateTopic: Error Handling
JavaScript Error Logging Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Simple error logger
class ErrorLogger {
log(error, level = 'error') {
const logEntry = {
level: level,
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
};
console[level](JSON.stringify(logEntry, null, 2));
}
}
const logger = new ErrorLogger();
try {
throw new Error('Test error');
} catch (error) {
logger.log(error);
}
// Method 2: Structured logging
class StructuredLogger {
log(error, metadata = {}) {
const logEntry = {
error: {
name: error.name,
message: error.message,
stack: error.stack
},
metadata: metadata,
timestamp: new Date().toISOString(),
environment: 'production'
};
console.error(JSON.stringify(logEntry));
}
}
// Method 3: Error levels
const LogLevel = {
DEBUG: 'debug',
INFO: 'info',
WARN: 'warn',
ERROR: 'error',
FATAL: 'fatal'
};
class LeveledLogger {
log(error, level = LogLevel.ERROR) {
const entry = {
level: level,
error: error.message,
timestamp: Date.now()
};
if (level === LogLevel.ERROR || level === LogLevel.FATAL) {
entry.stack = error.stack;
}
console.log(JSON.stringify(entry));
}
}
// Method 4: Error aggregation
class ErrorAggregator {
constructor() {
this.errors = new Map();
}
log(error) {
const key = error.message;
if (this.errors.has(key)) {
this.errors.get(key).count++;
} else {
this.errors.set(key, {
message: error.message,
count: 1,
firstSeen: Date.now(),
lastSeen: Date.now()
});
}
}
getSummary() {
return Array.from(this.errors.values());
}
}
const aggregator = new ErrorAggregator();
aggregator.log(new Error('Network error'));
aggregator.log(new Error('Network error'));
console.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 }]Understanding Error Logging
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
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.