What is util.debuglog() in Node.js?

The util.debuglog() method generates a function that conditionally writes to STDERR if the NODE_DEBUG variable exists in the environment variables.

The returned function works similarly to console.error() if the segment name exists within the value of that environment variable. If not, then the function is a no-op.

Prototype

util.debuglog(section, callback)

Parameters

  • section <string>: The section string identifies the part of the application for which the debuglog function is being made.
  • callback <function>: The callback function is invoked the first time the logging function is called with a function argument that is a more optimized logging function.

Return value

util.debuglog() returns the logging function created.

Code

const util = require('util')
const debuglog = util.debuglog('test')
debuglog('This is the debug string [%d]', 123);

Output

If the code is run with NODE_DEBUG=test in the environment variable, then debuglog('This is the debug string [%d]', 123) will print the debug string. Otherwise, it will not print anything.

The section argument can also take in wildcard arguments or multiple arguments separated with a comma.

For example, if the code is run with NODE_DEBUG=test* in the environment variables, then we can use any string that matches the pattern testany string starting with “test” as the section argument.

const util = require('util');
const debuglog = util.debuglog('test-section');
debuglog('hi there, it\'s test-section [%d]', 2333);

Output

The callback function is optional and can be used to replace the default logging function.

const { debug } = require('console');
const util = require('util');
let debuglog = util.debuglog('test', (debug) => {
console.log("Override the default behaviour here");
debuglog = debug;
});
debuglog("debug string");

Output

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved