Logging in Node.js

Logging is one of the most undervalued and most important features of an enterprise application. Logs is what makes a difference between spending sleepless nights catching a mysterious bug or reading a clear message about what exactly caused an application to crash. It is not just important to write logs. It is important to write logs in a right way. In this article we'll look at most popular Node.js logging solutions and how to use them in your application. console.log ----------------- Option #1 - console.log(). I never suggest to use it on a project that might go beyound your "hobby" folder. Still I see console.log() being used over and over again even in real applications! What are the downsides of console.log()? Firstly, you don't have a consistent and reliable way to capture the output to a persistent format (for example, file). So it is easy to lose your logs. Secondly, the logs from different components and of different severities will be mixed in one stream and thus spotting a problem (and isolating it), will be a real mission. Finally, console.log() might be blocking or non-blocking that will affect the performance of your app. Using console.log is not really a logging solution, so if you do it, read on and choose somethign better from a wide range of open-source tools and cloud services. Winston ----------------- Winston is a logging library that is much more suitable for a production use. Installing it is as simple as
  1. $ npm install winston
To configure winston, you need to configure a transport (or mutiple transports). A transport for logging is a "destination" - where your logs will go. For example, here's how you can save your logs in a file:
  1. const winston = require('winston');
  2. winston.add(winston.transports.File, {
  3. filename: 'application.log'
  4. });
Now whenever you call logger:
  1. winston.info('Application started');
It will add a line to your application.log. This feature becomes much more interesting if you think about the other possible transports. Just as easy as writing to the file, you can configure Winston to write to a database, TCP/IP socket, IRC channel, email, Redis or even cloud-based monitoring systems like Amazon SNS. Winston is my personal favorite logger and my default choice for new applications. Bunyan ----------------- The most distinguishable feature of Bunyan is that it logs JSON-formatted objects instead of strings. This makes it easier for scripts to parse logs and find the anomalies that you're looking for. Moreover, native support in JSON gives that missing structure to your log messages and opens a way to very interesting integration options. For example, Bunyan has an option to send messages to Slack or to Apache Kafka. Bunyan can also work with cloud services like Cloud Watch. Enogh theory, let's configure Bunyan for our project:
  1. npm install bunyan
Once all dependencies are there, time to initialise the logger.
  1. const log = bunyan.createLogger({
  2. name: 'appLog',
  3. streams: [{path: 'app.log.json'}]});
  4.  
  5. log.info('Application Started!');
Overall, Bunyan is a great tool to simplify integration with other tools. I like the idea, but I still prefer Winston. I like to be able to parse logs with simpler tools like cat + grep without having to dive into JSON formatting. Cloud Solutions ------------------ Nowdays we live in the era of "everything as a service". No wonder that there are multiple companies that provide log hosting, aggregation and analysis as a service too. Our review of logging wouldn't be complete without checking them out. http://logz.io/ - ELK based cloud solution with 1GB of free logs per day (a quite generous plan). You can also install your own version or ELK but that of course requires a bit more effort than signing up for logz.io (http://logz.io/blog/deploy-elk-production/) https://www.loggly.com/ - free 200Mb per day, Loggly will still be enough for most small applications. Loggly provides rich analytics on top of your logs with transaction correlation and trend spotting. https://papertrailapp.com/ - only 100 Mb per month on free tier, Papertrail is mostly focused on alerting. It has integrations with Web Hooks, Slack and email. These are just three tools out of many more avilable on the market. You should definitely give it a try and see which style works best for your app. Summary ------------ Logging is an important step for identifying bugs, reacting on dev-ops issues and correlating application performance with specific usage patterns. Even though console.log is widely available, it is not a great tool for an enterprise-gade application. Use Winston when you're looking for more "classic-style" logging or Bunyan for JSON-formatted logging and ease of integration. Besides, there are many "Logging as Service" platforms that you can try for free.

Add new comment