Skip to main content

One post tagged with "reactJS"

View All Tags

· 2 min read
Surya Shakti

Introduction

Frontend developers also need logs to access vital information. When things go wrong in production environment, the lack of usage of proper logging in the app may cause a lot of problems. Frontend developers may not even know about some problems if there is no proper logging. Every backend application have some level of logging structure for various purposes but we rarely see any proper structural logging in frontend.

In this article we will learn how we can store logs of React.js application into parseable using Pino library.

Creating a react application

Let's start with creating a react application. To create a react application run this comman in the terminal

npx create-react-app my-project-demo

Initializing pino in the app

To install pino in your application run the following command

npm install pino

Now in your src folder make a directory named loggers where we will initialize pino.js which will send logs to parseable. In /loggers/index.js paste this following code.

import pino from "pino";

const send = async function (level, logEvent, a, b) {
const url = "https://demo.parseable.io/api/v1/logstream/pinotest2";

const response = await fetch(url, {
method: "POST",
headers: {
Authorization: "Basic cGFyc2VhYmxlOnBhcnNlYWJsZQ==",
"Content-Type": "application/json",
},
body: JSON.stringify([logEvent]),
});
console.log(response);
};

const logger = pino({
browser: {
serialize: true,
asObject: true,
transmit: {
send,
},
},
});

export default logger;

In the above peice of code we are creating a logger instance through which we will send the logs of the application to parseable. In send method we are collecting the logs of the application and sending them to the parseable.

Now to use this logger instance we have to import it where ever we need and use it in place of console.An exapmle is shown below

import logger from "./loggers";
logger.info("test log! pinotest2 stream from reactjs application.");
function App() {
return <div className="App">ReactJs logs to parseable</div>;
}
export default App;

Conslusion

You have successfuly integrated parseable with your react.js application. Now you can run your application and all the events you have replaced with logger will be posted to parseable and you can check in the logstream you created earlier.

Happy Coding 🥳🥳...