The concept of instrumentation often refers to tracing where events happen in an application. Many application performance monitoring (APM) tools use it to provide metrics on the inner workings of your application. But sometimes, all you really need are details about API calls.

Adding a hook into every HTTP request your application makes will allow you to automatically log requests, monitor APIs, handle problems with failure remediations, and more. This holds true for both internal requests to your own services, but more importantly, it works with any request to external third-party APIs. Even those that use their own client SDK.

Creating a full system to manage this is a bit harder. You need a dashboard to view the metrics, storage to handle the logs, and a way to capture the data. Fortunately, the concept of HTTP instrumentation is easier in Node.js thanks to the ecosystem’s reliance on the underlying http module. Nearly every API client and request library used by node developers relies on this module.

In this post, we’ll look at the building blocks needed to add observability to every request your application makes. This means direct insight into your API calls, without the need to configure logging for each individually.

How it works

To make our instrumentation layer, we will patch the core methods of the http/https module. This means overriding their functionality, performing some action, then calling the original method. It sounds more complex than it is. To start, let’s look at a minimum example, without any new features. We can create a module in hijack.js as follows:

// hijack.js
const http = require("http")

function hijack() {
  override(http)
}

function override(module) {
  let original = module.request

  function wrapper(outgoing) {
    // Store a call to the original in req
    let req = original.apply(this, arguments)
    // return the original call
    return req
  }

  module.request = wrapper
}

module.exports = hijack

Let’s break down what this code is doing. We import the http module at the top. For a more complete version, we’d also need coverage for the https module. Next, the hijack function sets up the patches for http by calling an override function. The override function does three things:

  1. It makes a reference to the original request method.
  2. It creates a wrapper that accepts the original request parameters and returns the original, with the apply method called (more on this shortly).
  3. It overrides the original module’s request, module.request with our new wrapper function. This means http.request is now set to the wrapper function.

#nodejs #request #http-requests #http #logging #api

Instrumention and Monitoring API in Node.js
1.20 GEEK