package discovery: debug

2020-10-07

 | 

~1 min read

 | 

192 words

Another entry in my Package Discovery series. Today’s topic is logging using [debug, a debugging utility](https://www.npmjs.com/package/debug]!

Why use debug?

In many ways debug is just a glorified console.log. So why use it? A few reasons:

  1. Unlike console.log, a debug will not print by default. This gives you as an author of code control over the experience of users.
  2. debug allows for “namespacing” of logs, which means that you can have multiple different logs that are well organized.

Examples

From the README, we can see an example of how the namespacing works:

var a = require("debug")("worker:a"),
  b = require("debug")("worker:b")

function work() {
  a("doing lots of uninteresting work")
  setTimeout(work, Math.random() * 1000)
}

work()

function workb() {
  b("doing some work")
  setTimeout(workb, Math.random() * 2000)
}

workb()

Then, when this script is run, if debugging is turned on (notice the DEBUG=worker* glob), you might see logs like this:

multiple-debugs-for-workers

I’ve been looking for a tool like this to debug a CLI I’m building. Cannot wait to dive in and use it!



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!