Simple node debug logging

pavelloz

Paweł Kowalski

Posted on April 22, 2020

Simple node debug logging

While working on node.js programs, you often need to print some additional info on the screen to know what exactly is happening during the flow. In this article we will show you how you can improve your logging in a very simple way.

Before

There are nodejs packages to help you (listed in the end of the article) to abstract some parts and give some flexibility when it comes to filtering, but if you don't need much, you can just do an if statement:

if (process.env.DEBUG === 'true') {
  console.log("original filePath", filePath);
  console.log("extension", extension);
  console.log("mimeExtension", mimeExtension);
}
Enter fullscreen mode Exit fullscreen mode

Those console.logs will only work if there is a system environment variable DEBUG set to true.

For example, on *nix systems you can set the environment variable while running a command:

$ DEBUG=true pos-cli assets
Enter fullscreen mode Exit fullscreen mode

On Windows you should use set DEBUG=true.

This will result in something like this:

Before screenshot

It is doing what it's supposed to do, but we can do better with less code.

After

if (process.env.DEBUG === 'true') {
  console.log('Original data', {
    filePath,
    extension,
    mimeExtension
  });
}
Enter fullscreen mode Exit fullscreen mode
  1. We use Original data as the title for this object, which will help us identify what we are logging.
  2. In an object we use the shortcut version of key: value when both are the same by writing only key.
  3. In modern shells object values are colored (zsh on the screenshot).
  4. Logged object is formatted by nodejs, with indentations, further improving readability.
  5. If the object would fit in one line, nodejs would not break line and keep it compact.

Result

After screenshot

Other resources

There are some pretty nice alternatives if you want more power or visual clarity in your logging / debugging:

💖 💪 🙅 🚩
pavelloz
Paweł Kowalski

Posted on April 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related