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.
util.debuglog(section, callback)
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.util.debuglog()
returns the logging function created.
const util = require('util')const debuglog = util.debuglog('test')debuglog('This is the debug string [%d]', 123);
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);
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");
Free Resources