DEV Community

James
James

Posted on

2 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay