DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at on


TIL: Node.js has a built-in debug log method

Today I saw a quick conversation on Twitter between @ThisIsMisEm and @davidmarkclem, which unveiled an interesting fact about Node.js.

While millions of packages depend on the very popular debug package, it turns out that Node has similar functionality built-in via util.debuglog. Using it, you could maybe get rid of one dependency in your apps.

// index.js
const util = require('util');
const debuglog = util.debuglog('app');

debuglog('hello from my debugger [%d]', 123);
Enter fullscreen mode Exit fullscreen mode

When you run this code in your terminal, you won't see anything. However, when you set an environment variable NODE_ENV=app, the log messages appear:

$ NODE_DEBUG=app node index.js
APP 86155: hello from my debugger [123]
Enter fullscreen mode Exit fullscreen mode

util.debuglog even supports wildcards (*).

// index.js
const util = require('util');
const logGeneral = util.debuglog('app-general');
const logTimer = util.debuglog('app-timer');
const delay = 500;

logGeneral('Kicking off the app');

setTimeout(() => {
  logTimer('timer fired after %d', delay);
}, delay);
Enter fullscreen mode Exit fullscreen mode

Running the script with an app-* environment variable leads to the following:

$ NODE_DEBUG=app-* node index.js
APP-GENERAL 86188: Kicking off the app
APP-TIMER 86188: timer fired after 500
Enter fullscreen mode Exit fullscreen mode

The NODE_DEBUG environment variable can also be used to get debug messages from Node.js internals. You may have come across it in the Node.js documentation now and then.

It's good to know about util.debuglog but as David points out, it doesn't cover all the functionality of debug. debug for example colors your log messages nicely. The missing colors may not be a breaker for you but they are very welcome for lots of people debugging larger apps.

For me, util.debuglog will be a good alternative for debug in smaller projects and scripts.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!