Error Logging

Log errors effectively

IntermediateTopic: Error Handling
Back

JavaScript Error Logging Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// 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.

Practical Learning Notes for Error Logging

This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents