util.debuglog() Method in Node.js
×


util.debuglog() Method in Node.js

199

Introduction

The util.debuglog() method in Node.js allows you to create debug-specific logging functions that only print output when a certain condition is met, based on the NODE_DEBUG environment variable. This is especially useful for logging internal module messages during development without cluttering production output.

Syntax

util.debuglog(section)

The method returns a function that writes debug messages to stderr only when the section name matches what's set in NODE_DEBUG.

Parameter

  • section: A string (case-insensitive) used to filter logs. It identifies which debug logs should be active.

Return Value

Returns a logging function that behaves like console.log() but only outputs when debugging is enabled for the given section.

How It Works

Set the NODE_DEBUG environment variable to include the section name(s) you want to enable. When active, the returned debug function will log messages with a prefix showing the section and process ID.

Example


const util = require('util');
const debug = util.debuglog('server');

debug('Server started on port %d', 8080);
  

Running the Code

To see the output of the debug function, run the script with the NODE_DEBUG environment variable set to match the section name:

NODE_DEBUG=server node app.js

Output

SERVER 12345: Server started on port 8080

Here, 12345 represents the process ID.

Use Cases

  • Debugging internal components or modules without spamming output logs.
  • Selective logging during development.
  • Useful in large codebases to keep logs modular and easy to manage.

Conclusion

The util.debuglog() method is a lightweight way to handle conditional logging in Node.js. It helps developers keep logs clean and controlled without needing external libraries.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat