code

자동으로 모든 함수에 console.log 추가

codestyles 2020. 9. 6. 10:04
반응형

자동으로 모든 함수에 console.log 추가


어딘가에 (즉, 실제 함수 자체를 수정하지 않고) 전역 후크를 등록하거나 다른 방법을 통해 호출 될 때 함수 출력을 console.log 문으로 만드는 방법이 있습니까?


다음은 선택한 함수로 전역 네임 스페이스의 모든 함수를 확장하는 방법입니다.

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);
});

한 가지 단점 augment호출 후 생성 된 함수 에 추가 동작이 없다는 것입니다.


함수 호출을 기록하는 프록시 메서드

JS에서이 기능을 달성하기 위해 Proxy사용하는 새로운 방법 이 있습니다. 우리가 갖고 싶어한다고 가정 console.log특정 클래스의 함수가 호출 될 때마다 :

class TestClass {
  a() {
    this.aa = 1;
  }
  b() {
    this.bb = 1;
  }
}

const foo = new TestClass()
foo.a() // nothing get logged

클래스 인스턴스화를이 클래스의 각 속성을 재정의하는 Proxy로 바꿀 수 있습니다. 그래서:

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"

이것이 실제로 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.


If you want more targeted logging, the following code will log function calls for a particular object. You can even modify Object prototypes so that all new instances get logging too. I used Object.getOwnPropertyNames instead of for...in, so it works with ECMAScript 6 classes, which don't have enumerable methods.

function inject(obj, beforeFn) {
    for (let propName of Object.getOwnPropertyNames(obj)) {
        let prop = obj[propName];
        if (Object.prototype.toString.call(prop) === '[object Function]') {
            obj[propName] = (function(fnName) {
                return function() {
                    beforeFn.call(this, fnName, arguments);
                    return prop.apply(this, arguments);
                }
            })(propName);
        }
    }
}

function logFnCall(name, args) {
    let s = name + '(';
    for (let i = 0; i < args.length; i++) {
        if (i > 0)
            s += ', ';
        s += String(args[i]);
    }
    s += ')';
    console.log(s);
}

inject(Foo.prototype, logFnCall);

Here's some Javascript which replaces adds console.log to every function in Javascript; Play with it on Regex101:

$re = "/function (.+)\\(.*\\)\\s*\\{/m"; 
$str = "function example(){}"; 
$subst = "$& console.log(\"$1()\");"; 
$result = preg_replace($re, $subst, $str);

It's a 'quick and dirty hack' but I find it useful for debugging. If you have a lot of functions, beware because this will add a lot of code. Also, the RegEx is simple and might not work for more complex function names/declaration.


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);
    };
}());

You can actually attach your own function to console.log for everything that loads.

console.log = function(msg) {
    // Add whatever you want here
    alert(msg); 
}

참고URL : https://stackoverflow.com/questions/5033836/adding-console-log-to-every-function-automatically

반응형