Adding timestamps to all console messages

前端 未结 12 1124
鱼传尺愫
鱼传尺愫 2021-01-31 06:51

I have a complete, deployed, Express-based project, with many console.log() and console.error() statements throughout. The project runs using forever, directing the st

12条回答
  •  梦谈多话
    2021-01-31 07:38

    If you want a solution without another external dependency but you want to keep the full functionalities of console.log (multiple parameters, variable insertion) you can use the following code:

    var log = console.log;
    
    console.log = function () {
        var first_parameter = arguments[0];
        var other_parameters = Array.prototype.slice.call(arguments, 1);
    
        function formatConsoleDate (date) {
            var hour = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            var milliseconds = date.getMilliseconds();
    
            return '[' +
                   ((hour < 10) ? '0' + hour: hour) +
                   ':' +
                   ((minutes < 10) ? '0' + minutes: minutes) +
                   ':' +
                   ((seconds < 10) ? '0' + seconds: seconds) +
                   '.' +
                   ('00' + milliseconds).slice(-3) +
                   '] ';
        }
    
        log.apply(console, [formatConsoleDate(new Date()) + first_parameter].concat(other_parameters));
    };
    

    You can modify the formatConsoleDate function to format the date how you want.

    This code needs to be written only once on top of your main JavaScript file.

    console.log("he%s", "y") will print something like this:

    [12:22:55.053] hey
    

提交回复
热议问题