This article must be one of your first steps into learning what observability tools does and how you can start using them. During this article, we will be implementing Bugsnag on a Node.Js + Express project.
Check out the complete source code
- What are middlewares
- Setting up the project
- Creating the middleware (Optional)
- Testing the middleware (Optional)
- Sending the errors to a observability tool (Bugsnag)
- Final code
- Testing how the logs work
What are middlewares
Imagine that you want something to do something everytime your application receives a signal -- this signal can be a new request, an error, a subscription, a webhook, etc. -- in order to do some parsing with the received information... you are probably needing a new middleware for your application.
A middleware's main function is to intercept new requests (or events) and run a callback function using the received parameters, so, this way, you can go and do something with that data.
Setting up the project
Go ahead and install the base dependencies for a express application:
npm install express body-parser cors
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(cors());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
The code above is a base for you to start your new express server application with nodejs and javascript.
Creating the middleware (Optional)
To create a middleware with express, you need to use the .use()
method. This method will make sure that everything that happens in your application will be covered in that function (the middleware one).
app.use((err, req, res, next) => {
console.log("something broke");
});
// err -> If there is an error in the application, it will be stored on the err object.
// req -> The request object.
// res -> The response object.
// next -> The next middleware in the stack.
Testing the middleware (Optional)
We have not set any routes, so, if you go ahead and create a fake route to throw errors no matter what:
app.get("/", (req, res) => {
throw new Error("something went wrong");
});
Now, if you go ahead and make a GET request with:
curl http://localhost:3000
(or it could be using your Postman or other HTTP agent), you should see this error:
Sending the errors to a observability tool (Bugsnag)
First things first, you must go ahead and create an account at Busgnag.
After creating your account, select Express as a technology for your project and you should see this example code:
So, let us go ahead and follow those steps.
First, install bugsnag in your project
npm install @bugsnag/js @bugsnag/plugin-express --save
After installing bugsnag, replace the sample code in your project:
const Bugsnag = require('@bugsnag/js')
const BugsnagPluginExpress = require('@bugsnag/plugin-express')
Bugsnag.start({
apiKey: '<YOUR-API-KEY>',
plugins: [BugsnagPluginExpress]
})
Bugsnag have their own middleware service that does a abstraction of express middleware (the one that we have created), so, let us go and replace ours with the one that Bugsnag provides.
// This must be the first piece of middleware in the stack.
// It can only capture errors in downstream middleware
app.use(middleware.requestHandler)
/* all other middleware and application routes go here */
// This handles any errors that Express catches
app.use(middleware.errorHandler)
Final code
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Bugsnag = require("@bugsnag/js");
const BugsnagPluginExpress = require("@bugsnag/plugin-express");
Bugsnag.start({
apiKey: '<YOUR-API-KEY>',
plugins: [BugsnagPluginExpress],
});
const app = express();
app.use(bodyParser.json());
app.use(cors());
const PORT = process.env.PORT || 3000;
app.use(middleware.requestHandler);
app.get("/", (req, res) => {
throw new Error("something went wrong");
});
app.use(middleware.errorHandler);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Testing how the logs work
Now let us go and hit that error endpoint again with:
curl http://localhost:3000
If you have done all of the steps, in a minute or so you will be able to see data at your Bugsnag dashboard:
And that's it! Now you are able to see all of your server errors at Bugsnag and have a pretty good free-tier observability tool. To know more about pricing features, check it out here.
Liked this article? Show some love in the comments and follow me at Twitter.
Photo by Vadim Bogulov on Unsplash
Top comments (0)