Adding timestamps to all console messages

前端 未结 12 1095
鱼传尺愫
鱼传尺愫 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);

提交回复
热议问题