Thursday, September 22, 2022
HomeWordPress DevelopmentLogging on your Node.js app

Logging on your Node.js app




Introduction

On this article we are going to learn the way we are able to retailer logs of Node.js utility into parseable utilizing Winston library. We’ll take a look at what’s logging and why it is vital.



Desk of contents

  1. What’s logging?
  2. Utilizing winston in a Node.js utility
  3. sending these logs to the parseable



What’s logging?

Logging is the method of recording utility occasions and knowledge to a log file or another sources, for the aim of analyzing the system.

Logs assist builders to search out the error, observe the supply of the bug and repair it. In Node.js it’s crucial to construction the applying logs. once we are on the improvement section we are able to use console.log to search out the issues and to get the knowledge you want.

However as soon as the applying is in manufacturing we can not use the console.log any extra.



Utilizing winston in a Node.js utility

I assume you may have a node.js utility, now to put in winston & winston-transport in your mission run the next instructions.

npm set up winston
npm set up winston-transport
Enter fullscreen mode

Exit fullscreen mode

Now our intention is to interchange all of the console messages from the applying with the winston logger. So Only for instance if you happen to have these three occasion logs in your node.js utility which you wish to retailer in parseable utilizing winston library.

connsole.warn('Received mutiple parts with similar id');
console.error('Login Failed. Invalid ID');
console.information('Occasions posted efficiently.');
Enter fullscreen mode

Exit fullscreen mode

Configuring Winston in Node.js app

Create a ‘logger’ folder within the root listing the place we are going to configure winston and ship the logs to parseable.
Now in logger/index.js add following code

const winston = require("winston");
const { mix, timestamp, label, printf } = winston.format;
const Transport = require("winston-transport");
var axios = require("axios");

const myFormat = printf(({ degree, message, label, timestamp }) => {
  return JSON.stringify({
    timestamp: timestamp,
    degree: degree,
    message: message,
  });
});

class CustomTransport extends Transport {
  constructor(opts) {
    tremendous(opts);
  }
  log(information, callback) {
    console.information(information);
    var knowledge = JSON.stringify([info]);

    var config = {
      methodology: "publish",
      url: `https://demo.parseable.io/api/v1/logstream/${streamName}`,
      headers: {
        "X-P-META-Tag": "Proprietor",
        "X-P-META-Tag": "Host",
        "X-P-META-Tag": "Host.proprietor",
        Authorization: `Fundamental ${key}`,
        "Content material-Kind": "utility/json",
      },
      knowledge: knowledge,
    };

    axios(config)
      .then(perform (response) {
        console.log(response.knowledge);
      })
      .catch(perform (error) {
        console.log(error);
      });

    callback();
  }
}

const devLogger = () => {
  const transport = new CustomTransport({});

  return winston.createLogger({
    degree: "debug",
    format: mix(label(), timestamp(), myFormat),
    transports: [transport],
  });
};


let logger = null;

if (course of.env.NODE_ENV !== "manufacturing") {
  logger = devLogger()  
}

module.exports = logger;
Enter fullscreen mode

Exit fullscreen mode

Right here we’re configuring winston in our node.js utility and sending the logs to parseable.

Let’s talk about this code in components for higher understanding.

Initializing winston logger occasion

const devLogger = () => {
  const transport = new CustomTransport({});
  return winston.createLogger({
    degree: "debug",
    format: mix(label(), timestamp(), myFormat),
    transports: [transport],
  });
};

The snippet above comprises the initialization of a Winston logger occasion. Right here we specify the log degree for this particular logger occasion utilizing the npm log degree normal, format by which logs can be saved and


 that specifies the place the logs knowledge will go. In our case we are going to ship it to the parseable.



> **Setting customized format of the log knowledge**
>
>>

 ```js 
const myFormat = printf(({ degree, message, label, timestamp }) => {
  return JSON.stringify({
    timestamp: timestamp,
    degree: degree,
    message: message,
  });
});
Enter fullscreen mode

Exit fullscreen mode

The snippet above specifies the format of the log knowledge by which will probably be saved.

Sending the log knowledge to parseable

class CustomTransport extends Transport {
  constructor(opts) {
    tremendous(opts);
  }
  log(information, callback) {
    console.information(information);
    var knowledge = JSON.stringify([info]);
    var config = {
      methodology: "publish",
      url: `https://demo.parseable.io/api/v1/logstream/${streamName}`,
      headers: {
        "X-P-META-Tag": "Proprietor",
        "X-P-META-Tag": "Host",
        "X-P-META-Tag": "Host.proprietor",
        Authorization: `Fundamental ${key}`,
        "Content material-Kind": "utility/json",
      },
      knowledge: knowledge,
    };
    axios(config)
      .then(perform (response) {
        console.log(response.knowledge);
      })
      .catch(perform (error) {
        console.log(error);
      });
    callback();
  }
}

The snippet above is chargeable for sending the log knowledge to the parseable. right here streamName is the log stream you may have created in parseable. and the key is the authentication key for accessing the parseable.

calling the logger perform

let logger = null;
if (course of.env.NODE_ENV !== "manufacturing") {
  logger = devLogger()  
}

Chances are you’ll not wish to retailer the logs in parseable in improvement section then you possibly can see them on console to check it and when in manufacturing mode you possibly can ship it to parseable. The snippet above calls the logger perform in response to your necessities. you may also name the perform straight if you don’t need this conditional calling.

Then we are able to use logger as an alternative of console in our utility.

const logger = require('./logger')

logger.warn('Received mutiple parts with similar id')
logger.error('Login Failed. Invalid ID')
logger.information('Occasions posted efficiently.')
Enter fullscreen mode

Exit fullscreen mode



Conclusion

Hurray!!🥳🥳🥳

You’ve got efficiently built-in parseable along with your node.js utility. now you possibly can run your utility and all of the occasions you may have changed with logger can be posted to parseable and you’ll verify within the logstream you created earlier.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments