DEV Community

Omar Dulaimi
Omar Dulaimi

Posted on • Edited on

How to debug like a PRO in Nodejs?

Debug like a PRO with the 𝘂𝘁𝗶𝗹.𝗱𝗲𝗯𝘂𝗴𝗹𝗼𝗴 method.

It allows you write conditional debug messages to 𝘀𝘁𝗱𝗲𝗿𝗿 based on the existence of the 𝗡𝗢𝗗𝗘_𝗗𝗘𝗕𝗨𝗚 environment variable.

When the value passed match the one defined in your code, messages will be logged. Otherwise, these log statements will have no effect.

Obviously, this is a perfect feature for collecting debug logs in order to identify problems. Library authors use it, and I'm sure a lot of you noticed it with some of the libraries in the community.

As you can see in the snap, I'm running the code like this:
𝗡𝗢𝗗𝗘_𝗗𝗘𝗕𝗨𝗚=𝗮𝗽𝗽 𝗻𝗼𝗱𝗲 𝘀𝗮𝗺𝗽𝗹𝗲.𝗷𝘀

The options for the 𝘂𝘁𝗶𝗹.𝗱𝗲𝗯𝘂𝗴𝗹𝗼𝗴 method include:

𝘀𝗲𝗰𝘁𝗶𝗼𝗻: Name of the debug function for this portion of app.
𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸: Called only once. Can be used to replace the logging function.

Notes on the 𝗡𝗢𝗗𝗘_𝗗𝗘𝗕𝗨𝗚 env var:

  • It supports wildcard, so 𝗮𝗽𝗽* and * work.
  • You can specify multiple sections like this: 𝗮𝗽𝗽,𝗳𝘀,𝗻𝗲𝘁,𝘁𝗹𝘀 Which helps in filtering the debug logs to what you only care about.

Did you learn something new today?

Like and share this post, and follow me for more!

debuglog

Top comments (0)