Can I extend the console object (for rerouting the logging) in javascript?

前端 未结 6 1825
误落风尘
误落风尘 2020-11-30 08:33

Is it possible to extend the console object?

I tried something like:

Console.prototype.log = function(msg){
    Console.prototype.log.call(msg);
             


        
相关标签:
6条回答
  • 2020-11-30 08:59

    For ECMAScript 2015 and later

    You can use the newer Proxy feature from the ECMAScript 2015 standard to "hijack" the global console.log.

    Source-Code

    'use strict';
    
    class Mocker {
      static mockConsoleLog() {
        Mocker.oldGlobalConsole = window.console;
    
        window.console = new Proxy(window.console, {
          get(target, property) {
            if (property === 'log') {
              return function(...parameters) {
                Mocker.consoleLogReturnValue = parameters.join(' ');
              }
            }
    
            return target[property];
          }
        });
      }
    
      static unmockConsoleLog() {
        window.console = Mocker.oldGlobalConsole;
      }
    }
    
    Mocker.mockConsoleLog();
    
    console.log('hello'); // nothing happens here
    
    Mocker.unmockConsoleLog();
    
    if (Mocker.consoleLogReturnValue === 'hello') {
      console.log('Hello world!'); // Hello world!
      alert(Mocker.consoleLogReturnValue);
      // anything you want to do with the console log return value here...
    }
    

    Online Demo

    Repl.it.

    Node.js users...

    ... I do not forget you. You can take this source-code and replace window.console by gloabl.console to properly reference the console object (and of course, get rid of the alert call). In fact, I wrote this code initially and tested it on Node.js.

    0 讨论(0)
  • 2020-11-30 09:06

    You can override the default behavior of the console.log function using the below approach, the below example demonstrates to log the line number using the overridden function.

    let line = 0;
    const log = console.log;
    console.log = (...data) => log(`${++line} ===>`, ...data)
    
    console.log(11, 1, 2)
    console.log(11, 1, 'some')

    0 讨论(0)
  • 2020-11-30 09:09
    // console aliases and verbose logger - console doesnt prototype
    var c = console;
    c.l = c.log,
    c.e = c.error,
    c.v = c.verbose = function() {
        if (!myclass || !myclass.verbose) // verbose switch
            return;
        var args = Array.prototype.slice.call(arguments); // toArray
        args.unshift('Verbose:');
        c.l.apply(this, args); // log
    };
    
    // you can then do
    var myclass = new myClass();
    myclass.prototype.verbose = false;
    // generally these calls would be inside your class
    c.v('1 This will NOT log as verbose == false');
    c.l('2 This will log');
    myclass.verbose = true;
    c.v('3 This will log');
    

    I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.

    0 讨论(0)
  • 2020-11-30 09:12

    You Can Also add log Time in This Way :

    added Momentjs or use New Date() instead of moment.

    var oldConsole = console.log;
    console.log = function(){
        var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
        Array.prototype.unshift.call(arguments, timestamp);
        oldConsole.apply(this, arguments);
    };
    
    0 讨论(0)
  • 2020-11-30 09:18

    It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.

    var _console={...console}
    
    console.log = function(...args) {
        var msg = {...args}[0];
        //YOUR_CODE
        _console.log(...args);
    }
    
    0 讨论(0)
  • 2020-11-30 09:23

    Try following:

    (function() {
        var exLog = console.log;
        console.log = function(msg) {
            exLog.apply(this, arguments);
            alert(msg);
        }
    })()
    
    0 讨论(0)
提交回复
热议问题