Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show timestamp when logging with npm debug package in node.js?

I am using npm debug package to log messages to the console (instead of the regular console.log()). Is there a way to show timestamp of the message with this debug library? For example I'd like to display all log messages in the format:

debug("Server started")

And to get the output in a form:

[16:24:15] Server started

where 16:24:15 is the current time. Ideally I'd like to be able to specify the time format (eg. add milliseconds etc..).

like image 653
matori82 Avatar asked Aug 13 '18 13:08

matori82


1 Answers

Unfortunately the default debug formatting implementation is a little bit inflexible in this respect: there is no option to enable timestamps.

Here are three alternatives to enable timestamps:

  1. as mentioned previously: redirect stderr to a non-TTY handle, e.g. file or pipe. That disables colors by default and therefore switches to the format with timestamps
  2. use DEBUG_COLORS=no e.g.
$ DEBUG_COLORS=no DEBUG=* node ./dummy.js
Wed, 27 Feb 2019 12:29:12 GMT test Server started
  1. wrap/override the default implementation of debug.formatArgs(). This will be global for your program, i.e. you can only have one replacement. args is the array of the parameters pass into the debug() call, i.e. you can process all arguments, remove some entries or add entries.

F.ex.

'use strict';

const debug  = require('debug');
const logger = debug('test');

// wrap debug.formatArgs() implementation
const origFormatArgs = debug.formatArgs;
debug.formatArgs = function (args) { // requires access to "this"
    // example: prepend something to arguments[0]
    args[0] = `${new Date().toUTCString()} ${args[0]}`;

    // call original implementation
    origFormatArgs.call(this, args);
};

// override default debug.formatArgs() implementation
debug.formatArgs = function (args) { // requires access to "this"
    const name = this.namespace;
    const useColors = this.useColors;

    if (useColors) {
        // example: prepend something to arguments[0]
        args[0] = `${new Date().toUTCString()} ${name} ${args[0]}`;
    } else {
        // example: append something to arguments[0]
        args[0] = `${name} ${args[0]} ${new Date().toUTCString()}`;
    }
};

logger("Server started");
like image 151
Stefan Becker Avatar answered Sep 22 '22 12:09

Stefan Becker