Skip to content

Instantly share code, notes, and snippets.

@migliori
Created February 13, 2024 06:23
Show Gist options
  • Save migliori/dfa2ed3cbd1b536b2009246779008b1f to your computer and use it in GitHub Desktop.
Save migliori/dfa2ed3cbd1b536b2009246779008b1f to your computer and use it in GitHub Desktop.
Javascript logging proxy - logs constructor and method calls made to a target object #debug #log
/**
* This file contains a logging proxy implementation that can be used to log constructor and method calls made to a target object.
* The `createLoggingProxy` function creates a logging proxy for a target object, which logs all constructor and method calls made to the target.
* The `LoggedMyClass` class is an example usage of the logging proxy, where an instance of `MyClass` is wrapped with the logging proxy to log its calls.
* The purpose of this file is to provide a utility for logging and tracking calls made to objects, which can be useful for debugging and monitoring purposes.
*/
/**
* A counter for the number of calls made to the proxy.
* @type {number}
*/
let callIndex = 0;
/**
* Creates a logging proxy for a target object.
* The proxy logs all constructor and method calls made to the target.
*
* @param {Object} target - The target object to create a proxy for.
* @returns {Proxy} A proxy that logs all calls to the target.
*/
function createLoggingProxy(target) {
return new Proxy(target, {
construct: function(target, args) {
console.log(`Call ${++callIndex}: Constructor called with args: ${args}`);
const instance = new target(...args);
return new Proxy(instance, {
get: function(target, propKey, receiver) {
const origMethod = target[propKey];
if (typeof origMethod === 'function') {
return function (...args) {
console.log(`Call ${++callIndex}: ${propKey} called with args: ${args}`);
return origMethod.apply(this, args);
};
} else {
return origMethod;
}
}
});
}
});
}
/**
* A class that serves as an example for the logging proxy.
*/
class MyClass {
/**
* Constructs a new instance of MyClass.
*/
constructor() {
this.thing = null;
}
/**
* Calls the myFunc method of the MyClass instance.
*/
ini() {
this.myFunc();
}
/**
* Sets the thing property of the MyClass instance to 1.
*/
myFunc () {
this.thing = 1;
}
}
const LoggedMyClass = createLoggingProxy(MyClass);
const instance = new LoggedMyClass();
instance.ini();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment