Method Decorators for Instrumentation
You'll learn how to use method decorators to add logging, performance tracking, and validation around method calls without altering the method's core logic.
The Core Idea
Instrumentation means observing and measuring what your code does at runtime. Method decorators are perfect for this because they wrap existing methods with additional behavior — like a wrapper around a gift that records when it was opened and by whom, without changing the gift inside.
By applying decorators to methods, you can log every call, measure execution time, validate preconditions (like checking arguments), or enforce security rules — all without cluttering the actual method body with cross-cutting concerns.
How It Works
A method decorator receives the original method and context, then returns a replacement function. Inside that replacement, you run your instrumentation code before/after calling the original method:
function log(originalMethod, context) {
return function(...args) {
console.log(`Calling ${context.name} with`, args);
const result = originalMethod.call(this, ...args);
console.log(`${context.name} returned`, result);
return result;
};
}
function measure(originalMethod, context) {
return function(...args) {
const start = performance.now();
const result = originalMethod.call(this, ...args);
const duration = performance.now() - start;
console.log(`${context.name} took ${duration.toFixed(2)}ms`);
return result;
};
}
class Calculator {
@log
@measure
add(a, b) {
return a + b;
}
}
Each decorator wraps the method, creating layers of instrumentation that execute in order (bottom-up when stacked).
Key Takeaway:
Method decorators let you transparently inject instrumentation logic — logging, timing, validation — around methods without modifying their implementation, keeping business logic clean and observable.