/ Node.js

Best practices for logging in production for a Node.js application

There are several things you can do to set up logging in your Node.js server application. You'd want to be able to save your logs in a file so that you can keep track of them and also have a way to display logs only for debugging purposes. Here is what I think is the best and simplest way to achieve those.

No console.log()

You might have been using console.log() the entire time to log or debug your program. I know I have been using it. However, you should be using it sparingly, or even better not at all. The reason for that is that console.log() is synchronous and is slow (printing in a console generally is).

In a Node.js application, you would want to avoid synchronous calls as much as possible as they lock up processes. That means is that while a synchronous function is called (such as console.log), the program doesn't continue to run until the function completes running. Therefore, you'd want to make sure to avoid the logger from locking up your application, especially in a production environment.

Debug in development

Using console.log() in a development environment is completely fine as you'd want to use it to debug your application and you really won't be needing such fine-tuned performance gains. The trick is to get the logs to only show when you need to debug them.

A quick and simple way is to use the debug package.

debugnpm

It's basically a decorated console.log() that provides you with a simple way to toggle your debug logs. There are plenty of features in the package but simply put, you just have to give a name to your module and toggle the logs when based on what you need. Therefore, the logs are turned off by default and you are not going to have them run in your application when you are not debugging.

Logging in production

To log in a production environment, you'd want to log into a file to keep a copy of it to keep track. Besides that, you do not need the logs to output on the console and indirectly causing a performance hit. There are several logging libraries out there you can use and would depend largely on your preferences. Personally, I like to use winston for its simplicity but there are others use can use that provide more advanced features that you might like. Other alternatives you can check out are morgan and bunyan.

Winston

Best for general use. Easy to understand and simple to use.

Morgan

Great for access logs to keep track of client connections. Can be used for general logging as well.

Bunyan

Outputs in JSON format. Could be useful if you have a use case for it.

Wei-Ming Thor

Wei-Ming Thor

I am a programmer based in Kuala Lumpur, Malaysia. I write guides on programming and running a software business.

Read More