Back to results for “Monitoring”
Node.js › Debugging & Diagnostics

What is the DEBUG environment variable convention (popularized by the 'debug' npm package), and how does it let you enable verbose logging selectively?

Intermediate

Answer

The 'debug' package lets library and application code create namespaced debug loggers that are silent by default, only producing output when the DEBUG environment variable is set to match their namespace (supporting wildcards) -- this lets a developer enable exactly the verbose logging they need for a specific subsystem (like DEBUG=app:database) without being flooded by unrelated debug output from every other part of the application or its dependencies.
const debug = require('debug')('app:database');

function query(sql) {
  debug('Executing query: %s', sql); // silent unless DEBUG matches 'app:database'
  return db.execute(sql);
}

// DEBUG=app:database node server.js   -- shows only database debug logs
// DEBUG=app:*        node server.js   -- shows all app namespaces
// DEBUG=*             node server.js   -- shows everything, including dependencies using 'debug'
Real-world example A developer debugging a specific slow database query sets DEBUG=app:database before starting the server, getting detailed query-timing debug output only from the database layer, without being overwhelmed by verbose debug logs from Express's own internal routing, which also uses the same 'debug' package convention under a different namespace.

Common follow-ups: How does the 'debug' package achieve near-zero overhead when a given namespace isn't enabled?;Why is many popular npm libraries (like Express) already instrumented with 'debug' namespaces you can enable without any code changes of your own?