javascripthtmlloggingmetricsdatadog

Datadog post custom metrics from Browser


I am struggling to send data to custom metrics from Browser API. Docs are clear on how to do it from Node.js, but in Browser context it looks like there is no other option but to send it via HTTP request.

Did anyone find a browser's api method to do that, or did datadog just skip this feature for browsers?

The datatog in my web app is configured the CDN way:

    <script type="text/javascript" src="https://www.datadoghq-browser-agent.com/datadog-logs-us.js"></script>
    <script>
      DD_LOGS.init({
        // config
      });
    </script>

Solution

  • Datadog’s Browser SDK does not provide a direct API for sending custom metrics like the Node.js SDK does. Instead, the only way to send custom metrics from a browser is via HTTP requests to Datadog’s API.

    Send a request to Datadog’s metrics API:

    fetch("https://api.datadoghq.com/api/v1/series", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "DD-API-KEY": "your_api_key"
    },
    body: JSON.stringify({
      series: [
        {
           metric: "custom.metric.name",
           points: [[Date.now() / 1000, 42]], // timestamp in seconds, value
           type: "gauge",
           tags: ["env:production", "browser"]
        }
      ]
     })
    }).then(response => response.json()).then(console.log).catch(console.error);
    

    If you only need to track occurrences (not numerical metrics), use DD_LOGS.logger.info().

    DD_LOGS.logger.info("Custom event", { custom_metric_value: 42 });