Are you building a big project with Node.js? Learn how to build a logger lib for tracking errors and events.
When building a big Node.js app, as it gets bigger and you add more components, you ought to consider integrating a logging system to trace events on each component or store error information for detection later. We’re working on several small projects as part of a larger contract with a big food & beverage client in China, so we found it important to have a trace log feature to keep an eye on things. Let’s explore writing a logger lib with Node.js for better project-sharing.
First, I need to define the lib’s features:
Configurability for multi log steams, such as file storage for dev and syslog for production.
logger template, pre-defined template log template will help different project’s component sharing neat log format easily.
logger level can be changed in the code.
Second, I need pick some tools because I don’t want to start from scratch:
bunyan and winston are both very popular logging frameworks. The biggest difference is bunyan uses the JSON format, which makes logging big pieces of data more direct. Due to its simpler use for implementing the logger template, I’ll use bunyan.
bunyan-syslog is a plugin lib, which can help transfer logging data to Syslog. It works fine on my Mac, but watch out for your OS and version of Node.js, because it doesn’t support everything.
Also, for implementing logger template feature, I need an object validator lib for defining the logger schema. I use JOI lib, which has complete methods and active project management.
Let’s begin writing the lib.
Here is my lib’s bunyan-logger, you can see the details and ask questions there.
First step, write a steam factory for getting the logger steam configuration.