Why you should use Winston for Logging in JS
Tags: webdev, javascript, programming, tutorial
Published: 2024-06-05 05:17:26

# Logging with Winston in JS

Winston JS is a popular open-sourced Javascript logging library used to write logs in code with support extending upto multiple transport. A transport helps the log to be present at multiple levels, be it storage at database level but logs on the console.

The transports can be either console, database,  files or remote servers making it highly flexible to get logs as per the requirements. The core transports that are part of Winston are Console, File and HTTP while there is option to write logs in third-party transports like MongoDb, CouchDb  and Redis.  The additional transports are written by the members of Winston Community.

Moreover, there are different levels of a logger, set up in order of their priority in ascending order, specified by proposed standard of RFC 5424 in 2009.

[Pictorial Representation of Levels ](https://excalidraw.com/#json=ng5wxDOvU6v9HGlyYSjrq,yjd2OOWba2tFrzQh-lZtDQ)

## Setting Up Winston on Machine

Winston is available on npm to download and it is available to use on-the-go for those are looking for logging solution in their project. 

```bash
npm i winston
```
Upon successful installation of winston, we can proceed further with importing the library in our project to use it when required. It will be imported and automatically an object will be created that will come into use to access methods and attributes which are part of the object.
```javascript
const winston = require('winston');
```
## Creating First Logger

Once we are set up with installation and import part of Winston, we can proceed with creating our logger. We have a function at our disposal that is assist in creating a logger with all the necessary properties feeded in the passed object.

```javascript
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.MongoDB({
	    "db" : "mongodb://localhost/user"
    })
  ]
});
```
As mentioned in the above code, logger is created with set of transports given in an array, however in program, transports can be added, removed or clear as per developers requirement. 

```javascript
const file = new winston.transports.File({ filename: 'combined.log' })
logger
  .clear()          // Remove all transports
  .add(file)     // Add file transport
```
## Implementing Winston for Logging in a File
To obtain error logs in a file transport, we would be taking example of a full-fledged backend application based on Route-Controller-Service-Model Architecture. 

Initial step comprises of creating a file transport in the `index.js` file. 

```javascript
winston.add(winston.transports.File, { filename: "root.log"})
```
Now that we have our transport setup for the file named root.log to get the logging performed. We wireframe the connectivity in routing file named `route.js`.

```javascript
const express = require("express");
const app = express();

app.get('/', ()=> {
	throw new Error("Logging Error to the File");
})
```
Lastly, the invoking of error is performed that appends the error log to the file. 

```javascript
module.exports = (err, req, res, next) => {
	winston.error(err.message, err);
	res.status(500).send("Crashed into error");
}
```
## Implementing Winston for Logging in a MongoDB Collection

On instances, we come across errors that we fancy storing in our database instead of writing them to out files or console. We can move to store them as a MongoDB document in our collection specified. 

An additional winston-mongodb package is needed to work with the database. 
```bash
npm i winston-mongodb
```

Similar to logging in a file, create a MongoDB transport in the `index.js` file. 

```javascript
winston.add(winston.transports.MongoDB, { db: "mongodb://127.0.0.1/test"})
```
The code for route and error logging can be the same as mentioned in section for logging for file but results can be altered on the basis of level provided and transport method picked.

## Takeaways

- Winston is used to log errors.
- Winston offers multiple transport, place where log is stored.
- Winston offers flexibility when it comes to writing logs.
- Core transports that are bundled with Winston are Console, File and Http.
- Third-party transports includes MongoDB, Redis etc.
- Transports can be cleared, added or removed.
- Levels can be set for log o