How to control log messages without a dependency in Node.js (#tilPost)

Today I saw a quick conversation on Twitter between @ThisIsMisEm and @davidmarkclem. Their messages unveiled an interesting fact about Node.js debugging.
Millions of packages depend on the very popular debug package. The provided de…

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

Millions of packages depend on the very popular debug package. The provided debug method enables Node.js developers to control log messaging. Contrary to the good old console.log, messages using debug are hidden by default.

debug log messages are bound to a module name and will only appear when the DEBUG environment variable lists the particular module name.

// only logs message when `DEBUG=http` is set
const debug = require('debug')('http');

debug('booting %o', name);

util.debuglog – the native debug alternative

Section titled `util.debuglog` – the native `debug` alternative

It turns out that Node.js has a similar functionality built-in. The method util.debuglog provides almost identical functionality.

Let's have a look at a native example:

// 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 any log messages. However, when you define that you're intested in app log messages and define the environment variable NODE_DEBUG=app, the log messages appear:

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

util.debuglog even supports wildcards (*) in case you want to enable log messages for different modules at once.

// 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 perfect to know about util.debuglog, but as David points out, the native variant doesn't cover all of debug's functionality. Mainly, debug colors your log messages nicely and missing colors may be a breaker for a few people.

For me, util.debuglog is a good alternative for the debug package in smaller projects in which I want to save a dependency. If you want to learn more about Node.js and its util module, read the documentation for Node.js util or check out the Node.js section on my blog.


Reply to Stefan
Print Share Comment Cite Upload Translate
CITATION GOES HERE CITATION GOES HERE
Select a language: