Course contentsShow
← JavaScript
Lesson 2087 of 2,72343. DecoratorsFree lesson

Logging and Debugging Decorators

Use decorators to automatically log method calls, arguments, and return values for debugging purposes.

Logging and Debugging Decorators

You'll learn how to use decorators to automatically log method calls, arguments, and return values for debugging purposes.

The Core Idea

Imagine you're debugging a complex application and want to see every time certain methods are called, what arguments they receive, and what they return. Instead of manually adding console.log statements to every method (and then removing them later), you can create a decorator that does this automatically. It's like attaching a "surveillance camera" to your methods that records everything without cluttering your business logic.

How It Works

A method decorator receives the original function and can wrap it with logging logic before, after, or around the actual execution:

function log(method, context) {
  return function(...args) {
    const methodName = context.name;
    console.log(`[CALL] ${methodName}(${args.join(', ')})`);
    
    const result = method.call(this, ...args);
    
    console.log(`[RETURN] ${methodName} => ${result}`);
    return result;
  };
}

class Calculator {
  @log
  add(a, b) {
    return a + b;
  }
  
  @log
  multiply(a, b) {
    return a * b;
  }
}

const calc = new Calculator();
calc.add(5, 3);        // Logs: [CALL] add(5, 3)
                       //       [RETURN] add => 8
calc.multiply(4, 2);   // Logs: [CALL] multiply(4, 2)
                       //       [RETURN] multiply => 8

The decorator intercepts the method call, logs the details, executes the original method, logs the result, and returns it. You can add or remove the @log decorator without touching your actual method code.

Key Takeaway: Logging decorators wrap methods to automatically record calls, arguments, and return values, making debugging cleaner and more maintainable by keeping instrumentation separate from business logic.