Created
October 10, 2023 03:51
-
-
Save JamesGelok/89d4fdb63d06a378c6a74837930ab2ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addLoggingToMethods(classInstance: any) { | |
const originalMethods = {}; | |
// Store references to the original methods | |
for (const key of Object.getOwnPropertyNames(classInstance.prototype)) { | |
const method = classInstance.prototype[key]; | |
if (typeof method === 'function') { | |
originalMethods[key] = method; | |
} | |
} | |
// Create a counter to keep track of the method call order | |
let methodCallCount = 0; | |
// Modify the methods to include logging | |
for (const key of Object.getOwnPropertyNames(classInstance.prototype)) { | |
const method = classInstance.prototype[key]; | |
if (typeof method === 'function') { | |
classInstance.prototype[key] = function (...args: any[]) { | |
methodCallCount++; | |
console.log(`Call ${methodCallCount}: ${key} - Args: `, args); | |
return originalMethods[key].apply(this, args); | |
}; | |
} | |
} | |
} | |
// Example usage: | |
class ExampleClass { | |
constructor() { | |
// Initialize your class here | |
} | |
method1(arg1: any, arg2: any) { | |
// Your method logic here | |
} | |
method2(arg1: any) { | |
// Your method logic here | |
} | |
// Add more methods as needed | |
} | |
// Apply logging to the methods of ExampleClass | |
addLoggingToMethods(ExampleClass); | |
const exampleInstance = new ExampleClass(); | |
exampleInstance.method1("Hello", 42); | |
exampleInstance.method2("World"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment