Node.js has a built-in debug log method

2 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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);

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]

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);

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

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.

Related Topics

See null comment.