DEV Community

Omar Dulaimi
Omar Dulaimi

Posted on • Updated 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)