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..).
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:
stderr
to a non-TTY handle, e.g. file or pipe. That disables colors by default and therefore switches to the format with timestampsDEBUG_COLORS=no
e.g.$ DEBUG_COLORS=no DEBUG=* node ./dummy.js
Wed, 27 Feb 2019 12:29:12 GMT test Server started
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With