Añadir consola.registro de cada función automáticamente


Hay una manera de hacer que cualquier función de salida sea una consola.declaración de registro cuando se llama mediante el registro de un gancho global en algún lugar (es decir, sin modificar la propia función real) o a través de algún otro medio?

Author: JRL, 2011-02-17

5 answers

Aquí hay una manera de aumentar todas las funciones en el espacio de nombres global con la función de su elección:

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

Una desventaja es que ninguna función creada después de llamar a augment tendrá el comportamiento adicional.

 57
Author: Wayne Burkett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-15 19:54:54

Si desea un registro más específico, el siguiente código registrará las llamadas a funciones de un objeto en particular. Incluso puede modificar prototipos de objetos para que todas las instancias nuevas también obtengan registros. Usé Object.getOwnPropertyNames en lugar de for...in, por lo que funciona con las clases ECMAScript 6, que no tienen métodos enumerables.

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);
 1
Author: Peter Tseng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 05:10:54

Aquí hay algo de Javascript que reemplaza agrega consola.inicie sesión en cada función en Javascript; Juegue con ella en Regex101 :

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

Es un 'truco rápido y sucio', pero lo encuentro útil para la depuración. Si tiene muchas funciones, tenga cuidado porque esto agregará mucho código. Además, la expresión regular es simple y podría no funcionar para nombres/declaraciones de funciones más complejos.

 0
Author: hexicle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-25 05:35:47

Método proxy para registrar llamadas a funciones

Hay una nueva forma de usar Proxy para lograr esta funcionalidad en JS. supongamos que queremos tener un console.log cuando se llama a una función de una clase específica:

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

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

Podemos reemplazar nuestra instanciación de clase con un Proxy que anula cada propiedad de esta clase. así:

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"

Compruebe que esto realmente funciona en Codepen


Recuerda que usar Proxy te da mucho más funcionalidad que solo registrar nombres de consola.

También este método funciona en el nodo .js también.

 0
Author: Soorena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-25 15:44:05

En realidad puede adjuntar su propia función a la consola.registro para todo lo que carga.

console.log = function(msg) {
    // Add whatever you want here
    alert(msg); 
}
 -4
Author: Henrik Albrechtsson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-12 07:59:46