How I am using Winston to implement file logging in a NodeJS application?

How I am using Winston to implement file logging in a NodeJS application?

Winston is a NodeJS library for logging data on the server.

You can either log data on the console or on files.

Why use a Logger?

When we are developing codes or debugging an error, it's much easier if we have a stack trace rather than guessing. Nonetheless, most code analysis tools such as SonarQube don't like the presence of console logs. Additionally, once the amount of data increase, searching for relevant information becomes troublesome. Most terminals have a limit on visual.

Therefore, logging on files is a more effective solution. Moreover, if the data is saved in a particular format such as JSON, extracting it for analysis can be done with BI tools for instance.

Separate files

Depending on priority levels such as error, info and debug, you can separate them on different files.

The higher the level, the more data is logged, that is, the debug will log everything while the error will only log errors.

How I try using it efficiently?

Right now we are using the loggers in two ways, one highly efficient in my perspective while the other one requires a bit more work.

For the first, a middleware express logger is used which logs all the API requests in the files including the request and response objects. This gives a whole lot of an idea of what values are being passed, the headers and even errors when they occur.

The second approach is manually adding logs on objects being used, such as a Product. This is more helpful when coding or debugging the application, knowing if we are getting the expected result.

Log Rotate

I notice when using the application, the log files tend to grow quickly. In a system with hundreds of users, this can become a problem on the server. One way to deal with this, is by using log rotation.

The idea is to - on a daily or weekly basis - move the server logs onto another dedicated one for storage. These logs can later be retrieved for audit purposes if need be.