DEV Community

James
James

Posted on

Send metrics to Datadog from Netlify builds

I previously wrote about gathering Lighthouse audit metrics within CI. These and other custom metrics can be sent to Datadog for analysis without needing the Datadog agent. The implementation below uses Dogapi to send custom metrics via the Datadog API.

const {
  env: { DATADOG_API_KEY, VERSION, ENVIRONMENT },
} = require('process');

function createMetricReporter({ service }) {
  const dogapi = require('dogapi');
  const defaultTags = [`env:${ENVIRONMENT}`, `releaseVersion:${VERSION}`, `service:${service}`];
  const metrics = [];

  dogapi.initialize({
    api_key: DATADOG_API_KEY,
  });

  return {
    gauge: (metric, points, tags = []) => {
      metrics.push({
        metric,
        points,
        tags: [...tags, ...defaultTags],
        type: 'gauge',
      });
    },
    send: () => {
      const sendPromise = new Promise((resolve) => {
        dogapi.metric.send_all(metrics, (error, result) => {
          if (error) {
            console.log(`Unable to send metrics to Datadog`, error);
          } else {
            console.log(`Successfully sent metrics to Datadog`, result);
          }

          resolve(!error);
        });
      });

      return sendPromise;
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

Below is a snippet of what the Netlify plugin might look like.

module.exports = {
  onSuccess: async ({ inputs: { service, url, budget } }) => {
    const metrics = createMeticsReporter({ service });
    const results = await lighthouse(url, budget);

    for (const result of results) {
      const tags = [`formFactor:${result.formFactor}`];
      metrics.gauge('lighthouse.accessibility', result.accessibility, tags);
      metrics.gauge('lighthouse.bestPractices', result.bestPractices, tags);
      metrics.gauge('lighthouse.performance', result.performance, tags);
      metrics.gauge('lighthouse.pwa', result.pwa, tags);
      metrics.gauge('lighthouse.seo', result.seo, tags);
    }

    await metrics.send();
  },
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)