Adding timestamps to all console messages

前端 未结 12 1090
鱼传尺愫
鱼传尺愫 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:31

    If you wish, you may create a custom logger for your application by extending the Node's build in "Console" class. Kindly refer to the following implementation

    "use strict";
    
    const moment = require('moment');
    const util = require('util');
    const Console = require('console').Console;
    
    class Logger extends Console {
        constructor(stdout, stderr, ...otherArgs) {
            super(stdout, stderr, ...otherArgs);
        }
    
        log(...args) {
            super.log(moment().format('D MMM HH:mm:ss'), '-', util.format(...args));
        }
    
        error(...args) {
            super.error(moment().format('D MMM HH:mm:ss'), '-', util.format(...args));
        }
    }
    
    module.exports = (function() {
        return new Logger(process.stdout, process.stderr); 
    }());

    After that, you may use it in your code as :

    const logger = require('./logger');
    
    logger.log('hello world', 123456);
    logger.error('some error occurred', err);

    0 讨论(0)
  • 2021-01-31 07:34

    Use event listener like this,

    process.on('error', function() { 
       console.log('Error Occurred.');
    
       var d = Date(Date.now()).toString();
       console.log.call(console, d); // Wed Aug 07 2019 23:40:07 GMT+0100 (GMT+01:00)
    });
    

    happy coding :)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-31 07:38

    This isn't a direct answer, but have you looked into winston.js? It has a ton more logging options including logging to a json file or database. These always have timestamps by default. Just a thought.

    0 讨论(0)
  • 2021-01-31 07:39

    Create a file with the following:

    var log = console.log;
    
    console.log = function(){
      log.apply(console, [Date.now()].concat(arguments));
    };
    

    Require it in your app before you log anything. Do the same for console.error if needed.

    Note that this solution will destroy variable insertion (console.log("he%s", "y") // "hey") if you're using that. If you need that, just log the timestamp first:

    log.call(console, Date.now());
    log.apply(console, arguments);
    
    0 讨论(0)
  • 2021-01-31 07:39

    You could also use the log-timestamp package. It's quite straightforward, and customizable as well.

    0 讨论(0)
提交回复
热议问题