microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js
MIT License
323 stars 141 forks source link

Support for Fastify #627

Open murbanowicz opened 4 years ago

murbanowicz commented 4 years ago

Is it possible to provide out of the box support for Fastify instead of having to create custom trackers?

gboston commented 3 years ago

@murbanowicz Do you have an example on how you did the implementation with the custom trackers?

franher commented 2 years ago

There is some news on this issue? I'm trying to get endpoints metrics by default, but they do not appear on the Application Insights, so probably they must be implemented customly. Do you have some examples of such implementation with Fastify? It could be great to see something to start my custom implementation.

Thank you!

hectorhdzg commented 2 years ago

We are working on new version of the SDK using OpenTelemetry internally, you should be able to use fastify instrumentation library when this is available, https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node

evandeininger commented 2 years ago

@hectorhdzg Is there a place I can see the status of that work/when it's expected to be available? Thanks!

murbanowicz commented 1 year ago

@hectorhdzg I can see Fastify being pushed forward in that OT library, but how does it impact Application Insights auto instrumentation?

stefanpeer commented 3 months ago

I've created a plugin for this, as I noticed the autocollection did not work for a fastify project:

import { FastifyInstance, FastifyPluginOptions } from "fastify";
import fp from "fastify-plugin";
import appInsights from "applicationinsights";

declare module "fastify" {
  export interface FastifyRequest {
    app: { start: number };
  }
}

export const appInsightsPlugin = fp(
  async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
    if (!process.env.APPLICATIONINSIGHTS_CONNECTION_STRING) return;

    appInsights.setup().start();
    const client = appInsights.defaultClient;

    fastify.addHook("onRequest", async (request, reply) => {
      const start = Date.now();
      request.app = { start };
    });

    fastify.addHook("onResponse", async (request, reply) => {
      if (request.raw.url === "/") return; // Ignore health check

      const duration = Date.now() - request.app.start;
      client.trackRequest({
        name: request.raw.method + " " + request.raw.url,
        url: request.raw.url,
        duration: duration,
        resultCode: reply.statusCode.toString(),
        success: reply.statusCode < 400,
        properties: {
          method: request.raw.method,
          url: request.raw.url,
        },
        measurements: {
          duration: duration,
        },
      });
    });
  }
);