Adding console.log to every function automatically Adding console.log to every function automatically javascript javascript

Adding console.log to every function automatically


Here's a way to augment all functions in the global namespace with the function of your choice:

function augment(withFn) {    var name, fn;    for (name in window) {        fn = window[name];        if (typeof fn === 'function') {            window[name] = (function(name, fn) {                var args = arguments;                return function() {                    withFn.apply(this, args);                    return fn.apply(this, arguments);                }            })(name, fn);        }    }}augment(function(name, fn) {    console.log("calling " + name);});

One down side is that no functions created after calling augment will have the additional behavior.


As to me, this looks like the most elegant solution:

(function() {    var call = Function.prototype.call;    Function.prototype.call = function() {        console.log(this, arguments); // Here you can do whatever actions you want        return call.apply(this, arguments);    };}());


Proxy Method to log Function calls

There is a new way using Proxy to achieve this functionality in JS.assume that we want to have a console.log whenever a function of a specific class is called:

class TestClass {  a() {    this.aa = 1;  }  b() {    this.bb = 1;  }}const foo = new TestClass()foo.a() // nothing get logged

we can replace our class instantiation with a Proxy that overrides each property of this class. so:

class TestClass {  a() {    this.aa = 1;  }  b() {    this.bb = 1;  }}const logger = className => {  return new Proxy(new className(), {    get: function(target, name, receiver) {      if (!target.hasOwnProperty(name)) {        if (typeof target[name] === "function") {          console.log(            "Calling Method : ",            name,            "|| on : ",            target.constructor.name          );        }        return new Proxy(target[name], this);      }      return Reflect.get(target, name, receiver);    }  });};const instance = logger(TestClass)instance.a() // output: "Calling Method : a || on : TestClass"

check that this actually works in Codepen


Remember that using Proxy gives you a lot more functionality than to just logging console names.

Also this method works in Node.js too.