Node.js – util.debuglog() Method


The util.debuglog() method creates a function that can be used to write the desired error/debug messages to stderr. These error messages are written only upon the existence of the NODE_DEBUG environment variable.

Syntax

util.debuglog(section, [callback])

Parameters

The parameters are described below −

  • section − This parameter takes the portion of the application for which the debug log is being created.

  • callback − This is the callback function which will receive the pointer if any error occurs during the execution of method.

Example 1

Create a file with the name "debuglog.js" and copy the following code snippet -

 Live Demo

// util.debuglog() demo example

// Importing the util module
const util = require('util');

const debugLog = util.debuglog('application#1');

// Use debuglog() method
debugLog('Welcome to Tutorials Point');

let debug = util.debuglog('application#2',
   (debuging) => {
      // Replace with a logging function
      // that optimizes out
      a = "new Value";
      // Testing if the section is enabled
      debug = debuging;
});

// prints the debuglog function
console.log(util.inspect(debug,
      showHidden = true, compact = true));

// logs app *
debug();

debug('Hello User #[%d]', 2);

Use this following command to run the above application in debug mode -

NODE_DEBUG=application* node debuglog.js

Output

C:\home
ode>> NODE_DEBUG=application* node debuglog.js APPLICATION#1 337356: Welcome to Tutorials Point { [Function: debug]    [length]: 0,    [name]: 'debug',    [prototype]: debug { [constructor]: [Circular] } } APPLICATION#2 337356: APPLICATION#2 337356: Hello User #[2]

Example 2

Let’s have a look at one more example -

 Live Demo

// util.debuglog() demo example

// Importing the util module
const util = require('util');

const debuglog = util.debuglog('application');

debuglog('Hello [%s], - From Tutorials Point', 'user');

const generalLog = util.debuglog('app-');
const timerLog = util.debuglog('appl');
const delay = 200;

// Printing the log for 'app-'
generalLog('Exiting app-');
console.log("Waiting for Timer Log to get executed")
// Timer will run after 200 ms
setTimeout(() => {
   timerLog('Timer is fired after %d ', delay);
}, delay);

Output

C:\home
ode>> NODE_DEBUG=application* node debuglog.js APPLICATION 338111: Hello [user], - From Tutorials Point APP- 338111: Exiting appWaiting for Timer Log to get executed APPL 338111: Timer is fired after 200

Updated on: 18-Aug-2021

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements