blog image
Blog Articles

Implementing a Custom Logger with Winston in Node.js

Introduction

This article guides you through the process of crafting a customized logger for Node.js applications, a crucial aspect in the development of various software solutions, including web applications, real-time chat applications, streaming applications, and more.

While working on a personal project, I found myself pondering the effective tracking of errors and event flow in a production environment, a concern applicable across diverse domains such as web development services, custom financial software development, iOS mobile app development, software development in healthcare, and QA software testing services. This curiosity naturally led me to explore the concept of logs, essential not only for debugging but also for maintaining the integrity and performance of applications.

In essence, a log file is a repository of records that document events transpiring during the execution of an application, making it an integral component for banking software development companies, custom enterprise software development, and financial software development services. In the log file, each individual record, regardless of the application type, refers to itself as a log. Armed with this fundamental understanding of logs, I delved deeper and uncovered three pivotal questions, prompting me to share my insights through this blog. Let’s explore these questions and the corresponding answers, applying the knowledge gained to various scenarios such as mobile app development and software testing.

When do we use logs?

Developers adopt various custom logging strategies based on their application’s nature and purpose. 

Some common approaches include:

  1. Logging exclusively during error occurrences or unexpected behavior.
  2. Logging solely in debug mode.
  3. Logging in response to specific events.

The selection of a particular approach, or a combination thereof, is a decision left to the developer. In the context of this blog, where the focus is on creating a RESTful API intended for widespread use, I opted for the third approach—logging all significant events.

What do we log?

Determining what to log depends largely on the specific requirements of the application, whether it’s a custom financial software development project or a mobile app development endeavor. For instance, when developing a REST API intended for widespread use, it becomes valuable to log crucial details such as the timestamp, event description, and the content or parameters of the request. This comprehensive information aids in distinguishing logs associated with a particular user, a consideration particularly relevant in software development in healthcare.

Consider a scenario where a user encounters an error and reaches out to the developer for assistance, a situation commonly addressed by QA software testing services. In such cases, developers typically require only the user ID (assuming it is included in the request body) and/or the timestamp of the request to effectively pinpoint the issue. The logging implementation includes the following key components, applicable across banking software development companies, custom enterprise software development, and financial software development services:

How can you implement a logger for a Node application?

To implement a logger for your Node.js application, you can leverage popular npm modules such as Morgan, Bunyan, or Winston. Among these, Winston stands out for its ease of use in building custom logs, as illustrated in Figure 2.

Follow the steps below to integrate a custom logger into your Node application. You can skip the initial instruction if you’ve already set up a Node project.

Note: This guide assumes that you have Node installed, have set up VS Code, and configured an npm path.

Now, let’s proceed with the implementation.

1. Create a Node project

To start your Node.js project, create a new folder (I’ve named it “LoggerWinston”). Open the folder in VS Code and execute the following command in the terminal:

Fill in the prompted details or skip by pressing Enter. Upon completion, the process generates a JSON file named package.json in your folder.

2. Install the required modules

Next, install the necessary modules. Since we’ve chosen Winston for building the custom logger, install it by running the following command:

Additionally, we’ll use Express to construct the API endpoint and the body-parser middleware to access the request body. Install them with the following command:

With these modules installed, you’re ready to proceed with building your custom logger for the Node.js application.

3. Creating the Custom Logger class

Organize your project by creating a “services” folder. Inside this folder, generate a file named “loggerService.js” and copy-paste the provided code:

If you desire to modify the log messages, you can easily achieve this by editing the return statement within the format attribute of the object inside the winston.createLogger() method. This provides a straightforward way to customize the content of your log entries through nodejs console logger.

For a more extensive adjustment of the log format, you can refer to the documentation or resources related to Winston docs. The flexibility of Winston allows you to tailor the log format to suit your specific requirements, providing detailed control over how information is presented in your logs. Explore the available options and tailor the log format according to your preferences.

4. Creating /logger POST API endpoint to test the logger

In the main folder, establish a file named “app.js” and insert the provided code:

The provided code snippet defines a basic validation endpoint in the “app.js” file. This endpoint receives a JSON payload and performs a validation check to determine if any of the values are empty or null. Depending on the validation result, the endpoint responds with either “Error” or “No Error.”

5. Running the Node Application and Testing the /test endpoint created

Execute the following command in your terminal to start the server:

Upon initiating the server, you will observe a log in the terminal. Additionally, you should find an “app.log” file inside the “logs” folder; the log entries displayed in the terminal are also stored in this file.

This dual logging mechanism provides a convenient way to access real-time information in the terminal while maintaining a persistent record in the log file for future reference or analysis. Adjust the log file names or paths as needed based on your project’s structure and requirements.

Testing the Endpoint

Now, proceed to test the endpoint using a testing tool; in this instance, Postman is utilized. Craft a request with the following JSON in the request body. Note that the userName attribute is intentionally left empty to trigger an error response, providing an opportunity to investigate the issue through the logs.

This deliberately crafted request allows you to simulate a scenario where a required field (userName in this case) is empty, triggering the error handling mechanism. By examining the logs of nodejs console logger, you can gain insights into the nature of the error and pinpoint the source of the issue for effective debugging. Adjust the request payload as needed to test various scenarios and observe the corresponding log entries for thorough validation.

Configure the Postman request to match the specifications outlined in the provided image.

Following the configuration as depicted in Figure 4, send the request and examine whether the response contains an error message.

Subsequently, track the log file to pinpoint the exact error. Open the log file, which is likely named “app.log” based on the previous setup, and inspect the entries related to the recent request. The custom logger, configured with Winston, logs detailed information about the events, including error messages and timestamps. By analyzing these logs, you can gain valuable insights into the nature of the error, aiding in effective debugging and issue resolution.

Important Tip

Ensure to review the log entries for the specified timestamp corresponding to when the request was made. This approach facilitates a systematic investigation of the logs of nodejs console logger, allowing you to identify and address the specific issues encountered during the request. Adjust the request payload or simulate different scenarios to further explore the capabilities of the custom logger in tracking and handling errors.

If you’ve diligently followed the provided instructions, your output should resemble above image. The third log represents the error log, effectively allowing us to identify and understand the error through the logs.

Now, for further validation, modify the values in the request body JSON within Postman. Test different scenarios to verify if the corresponding logs are generated as expected. This process helps ensure that the custom logger is capturing relevant information for a variety of situations.

By iteratively adjusting the request payload and observing the logged entries in the file, you can thoroughly evaluate the logging functionality. This iterative testing approach is crucial for validating the effectiveness of the custom logger across diverse scenarios, enabling you to confidently rely on it for error tracking and debugging in your Node.js application.

Conclusion

In conclusion, implementing a custom logger with Winston in a Node.js application equips developers with a robust tool for managing and analyzing nodejs console logger for custom logs efficiently. Winston’s flexibility and extensibility make it a valuable asset in ensuring effective monitoring, debugging, and overall system health. By tailoring the nodejs console logger to specific application needs, developers can gain granular insights into their code execution, enhancing the maintainability and performance of their Node.js projects.

Sign Up Now
Get a Fast Estimate on Your Software Development Project

We are committed to delivering high-quality IT solutions tailored to meet the unique needs of our clients. As part of our commitment to transparency and excellence, we provide detailed project estimations to help our clients understand the scope, timeline, and budget associated with their IT initiatives.

Related Post

Mastering Role-Based Access Control in Mean Stack

In the ever-evolving realm of web development, safeguarding user data and system functionalities is a top priority. Role-Based Access Control (RBAC) stands as a formidable defense, providing a methodical framework…

View Article
Microservices Architecture with Node.js and Docker

Introduction As a leading force in the tech industry, we specialize in a wide array of services tailored to meet the diverse needs of businesses across various sectors. From custom…

View Article
Cloudinary Integration Guide

If you are looking for a powerful cloud-based imaging solution, look no further than Cloudinary. This comprehensive platform offers a wide range of functionalities, from image manipulation and optimization to…

View Article