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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more