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>: Thesectionstring identifies the part of the application for which thedebuglogfunction is being made.callback <function>: Thecallbackfunction 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 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