DEV Community

David Pereira
David Pereira

Posted on

A small tip for debugging a Node.js app

debug gif

Source from GIPHY

Introduction

I recently came across a bug in production (or what appears to be a bug), but I couldn't really track the source of the problem. From the description I was given (screenshots and text) I kinda knew where the error could have happened... but I didn't know how 😵. I mean... really, how did this happen?! I tried to simulate the bug on a staging environment and on my local machine first, but the code worked as expected.

It was through my colleague that I got introduced to this npm module that I'll talk about next, and I consider it to be a very useful tool in troubleshooting problems.

This short post is aimed at helping you troubleshoot better when there are bugs in your Node.js app. So let's get right into it!

Debug module

I was not aware of the debugging capabilities of Express.js and after I learned this, I came across this debug npm module. You can use it to create a tracing log function, and add extra information so that you have the values you need to "simulate" what happened in a section of your code. To create this trace function you just need this code:

import createDebug from 'debug'
const debugLog = createDebug(`server:<my module name>`)
const trace = debugLog.extend('trace')
Enter fullscreen mode Exit fullscreen mode

The parameter you pass to the createDebug function is the name of your module, but I added a prefix to it - "server:". This is a convention of the library that allows you to separate features. If you're interested check more info. here.

Then you can use it simply like this:

const isEmpty = //...
trace(`logging my vars... isEmpty:${isEmpty}`)
Enter fullscreen mode Exit fullscreen mode

or to format better some values, like arrays, you can use the library's formatters:

const arrayWithGoodies = ["sup", "hello", "bugs happen...", "so we need to " + ]
trace('arrayWithGoodies: %O', arrayWithGoodies)
Enter fullscreen mode Exit fullscreen mode

You can also create other functions like these and each one has it's own color, that I believe can be configurable:

const info = debugLog.extend('info')
const warn = debugLog.extend('warn')
const error = debugLog.extend('error')
Enter fullscreen mode Exit fullscreen mode

Conclusion

I'm sure there are a lot more interesting features in this library, but that's all I know for now. I hope you enjoyed reading this small post. Leave a comment with any feedback, and I'd gladly respond 😃.

Check out my previous post What is production-ready code, where I write about some of the code properties that software developers are expected to know.

Top comments (0)