gitmyhub

debug

JavaScript ★ 11k updated 2mo ago

A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers

A tiny JavaScript utility that lets you add labeled diagnostic log messages to your code and turn specific groups on or off with an environment variable, replacing scattered console.log calls.

JavaScriptNode.jssetup: easycomplexity 2/5

The debug package is a small JavaScript utility for printing diagnostic messages during development. Instead of scattering regular console.log calls throughout your code that you then have to remove before shipping, you label each message with a namespace and turn entire groups of messages on or off with an environment variable. Only the messages you care about right now show up; everything else stays silent.

You install it like any other JavaScript package and use it by creating a named logger for each part of your code. For example, a module called "worker" might have two loggers, "worker:a" and "worker:b". Setting the DEBUG environment variable to "worker:*" turns both on at once. You can also exclude specific namespaces by prefixing them with a minus sign, so "DEBUG=*,-worker:a" would show everything except that one.

Each namespace gets its own color in the terminal output, which helps when multiple parts of an application are logging at the same time. Debug also shows how much time passed between consecutive calls to the same logger, which can help spot where an application is slow. When output is not going to a terminal, timestamps switch to a standard date format more suited to log files.

The library works both in Node.js (server-side JavaScript) and in web browsers, where the browser's developer tools console displays the colored output. In the browser, the list of enabled namespaces is saved in localStorage so your debug settings persist across page reloads.

Formatting follows the printf style familiar from C and other languages, with built-in support for strings, numbers, JSON, and object pretty-printing, plus the ability to register custom formatters.

Where it fits