Logging in Node.js Using Winston: Best Practices
Hi Everyone,
Hope everyone is safe and doing well!
We use console.log very often in any javascript application. It helps us in debugging, monitoring, improving performance, understand the logic,etc.
If the application is used on small scale you might think creating custom logs are overwork, but once the application turns out to be production with large user base, keeping a track of all the console.log in a single file would be very difficult to observe and analyze.
So creating a logger with custom log levels in a persistent file system would help us easily analyze the issues and bugs in our system.
For example, we have all our errors in one file the info & warnings in another file which is rotated/moved to a new file on a daily basis. This would help us easily use commands like sed/awk to filter out the logs for a specific case.

In node.js we have a very popular library for logging called “winston”
We’ll go through how to implement winston in our project.
1. Install Winston
npm install winston
npm install winston-daily-rotate-file
2. Create a file quick-logger.js
I have created the file inside services/_helper

3. Configure winston in quick-logger.js
Let's go through what we are doing here.
After importing createrLogger from Winston , we need to pass our config to it.
Log Levels :
There are various Log levels present
Info: Various info for code flow and execution
Error: Logs to find where code execution fails
Warn : Code that is probable to fail
Debug: Can be used to debug code
Formatting
Winston provides formatting to logs , there are various built-in formats (link) that help us in easily analyzing the logs. Here we are combining various formats to build a custom logger.
Transport :
Winston transport helps us in the storage of the logs. It can be a local file or a database. Winston by default provides Console, File, Http, and stream. Apart from these, there are various community-driven transports created that help in logging to AWS, ElasticSearch, etc. You can find all compatible transporters here (Winston-Transports)
Here in transport key (line no 25–34) we are writing error level logs to a file name ‘app-error.log’ and all the combined logs to a file named app-combined.log.
Rotating logs
We have used a custom transport ‘winston-daily-rotate-file’ which is useful in rotating the logs on time basis(hourly/daily/weekly..) or size basis (1 MB, 1 GB..). Here datePattern: ‘YYYY-MM-DD’
identifies that the logs would be rotated in daily basis.

You can also explore more on writing logs to DB/ElasticSearch using custom transports available.
If we are not in a production environment we are also writing the logs to console for easy development and debugging using the Console transport provided by Winston(line no 42–49 )
Note : create a folder path as /var/log/your-project
4. Using the custom logger
Once we have created the quick-logger.js file. We can start using it in our codebase. We should try to replace the all the console.log in our project with the winston logger.
We can import the logger in our server.js (index file ) and then assign it to global variable of node such that it is available throughout the project.
const logger = require('./services/_helper/quick-logger');
global.logger = logger
Now logger is available throughout the project
let copyObj = {var1:"Abc",var2:"xyz"}
logger.info("Auditing UserController",{
customlog:'AUDIT',
type:"REQUEST",
api:"LOGINUSER",
req:copyObj
})
Here the first param to the function is a message and the second param will be a custom object that will be printed to the logs.
Note: the defaultMeta provided in config would be concatenated with the above object.
Tips: here I have created various keys in an object which would help me in segregating/filtering logs in future.
I have created the key api:”LOGINUSER”
, so if in the future I want to see the logs related to login API, I can easily filter it out.
Try creating keys that would help you understand your logs clear.
Conclusion
We have seen how we can implement logging in Node.js application for custom logs. Logging can be helpful in debugging and analyzing your code performance. Set up a proper logging system in your application as it can be a great life-saviour.
Thanks for reading! If you found this article helpful do share it!
Do follow me on LinkedIn: https://www.linkedin.com/in/manishbit97/
Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.