Métriques
Rapport de recherche Datadog : Bilan sur l'adoption de l'informatique sans serveur Rapport : Bilan sur l'adoption de l'informatique sans serveur

Métriques

Les endpoints de métriques vous permettent :

  • D’envoyer des données de métriques afin de les représenter graphiquement sur les dashboards de Datadog
  • D’interroger vos métriques sur l’intervalle de votre choix

Remarque : un graphique ne peut contenir qu’un nombre défini de points. Lorsque l’intervalle d’affichage d’une métrique augmente, les points sont agrégés afin de ne pas dépasser ce nombre.

Datadog applique une limite souple de 100 séries temporelles par host. Une série temporelle désigne une combinaison unique d’un tag et d’un nom de métrique.

Modifier les métadonnées d'une métrique

PUT https://api.datadoghq.eu/api/v1/metrics/{metric_name}https://api.datadoghq.com/api/v1/metrics/{metric_name}

Présentation

Modifiez les métadonnées d’une métrique spécifique. En savoir plus sur les différents types pris en charge.

Arguments

Paramètres du chemin

Nom

Type

Description

metric_name [required]

string

Name of the metric for which to edit metadata.

Requête

Body Data (required)

Nouvelles métadonnées.

Expand All

Champ

Type

Description

description

string

Metric description.

integration

string

Name of the integration that sent the metric if applicable.

per_unit

string

Per unit of the metric such as second in bytes per second.

short_name

string

A more human-readable and abbreviated version of the metric name.

statsd_interval

int64

StatsD flush interval of the metric in seconds if applicable.

type

string

Metric type such as gauge or rate.

unit

string

Primary unit of the metric such as byte or operation.

{
  "description": "string",
  "per_unit": "second",
  "short_name": "string",
  "statsd_interval": "integer",
  "type": "count",
  "unit": "byte"
}

Réponse

OK

Object with all metric related metadata.

Expand All

Champ

Type

Description

description

string

Metric description.

integration

string

Name of the integration that sent the metric if applicable.

per_unit

string

Per unit of the metric such as second in bytes per second.

short_name

string

A more human-readable and abbreviated version of the metric name.

statsd_interval

int64

StatsD flush interval of the metric in seconds if applicable.

type

string

Metric type such as gauge or rate.

unit

string

Primary unit of the metric such as byte or operation.

{
  "description": "string",
  "integration": "string",
  "per_unit": "second",
  "short_name": "string",
  "statsd_interval": "integer",
  "type": "count",
  "unit": "byte"
}

Bad Request

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Forbidden

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Not Found

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        # Path parameters
export metric_name="CHANGE_ME"
# Curl command curl -X PUT "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/metrics/${metric_name}" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}" \ -d @- << EOF {} EOF
package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },
        },
    )

    metricName := "metricName_example" // string | Name of the metric for which to edit metadata.
    body := *datadog.NewMetricMetadata() // MetricMetadata | New metadata.

    configuration := datadog.NewConfiguration()

    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.UpdateMetricMetadata(ctx, metricName).Body(body).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.UpdateMetricMetadata``: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `UpdateMetricMetadata`: MetricMetadata
    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.UpdateMetricMetadata`: %v\n", resp)
}
// Import classes:
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.auth.*;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.MetricsApi;

public class Example {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // Configure the Datadog site to send API calls to
        HashMap<String, String> serverVariables = new HashMap<String, String>();
        String site = System.getenv("DD_SITE");
        if (site != null) {
            serverVariables.put("site", site);
            defaultClient.setServerVariables(serverVariables);
        }
        // Configure API key authorization: 
        HashMap<String, String> secrets = new HashMap<String, String>();
        secrets.put("apiKeyAuth", System.getenv("DD_CLIENT_API_KEY"));
        secrets.put("appKeyAuth", System.getenv("DD_CLIENT_APP_KEY"));
        defaultClient.configureApiKeys(secrets);

        MetricsApi apiInstance = new MetricsApi(defaultClient);
        String metricName = "metricName_example"; // String | Name of the metric for which to edit metadata.
        MetricMetadata body = new MetricMetadata(); // MetricMetadata | New metadata.
        try {
            MetricMetadata result = apiInstance.updateMetricMetadata(metricName)
                .body(body)
                .execute();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling MetricsApi#updateMetricMetadata");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}
import os
from dateutil.parser import parse as dateutil_parser
import datadog_api_client.v1
from datadog_api_client.v1.api import metrics_api
from datadog_api_client.v1.models import *
from pprint import pprint
# Defining the host is optional and defaults to https://api.datadoghq.com
# See configuration.py for a list of all supported configuration parameters.
configuration = datadog_api_client.v1.Configuration(
    host = "https://api.datadoghq.com"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure API key authorization: apiKeyAuth
configuration.api_key['apiKeyAuth'] = os.getenv('DD_CLIENT_API_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['apiKeyAuth'] = 'Bearer'

# Configure API key authorization: appKeyAuth
configuration.api_key['appKeyAuth'] = os.getenv('DD_CLIENT_APP_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['appKeyAuth'] = 'Bearer'

# Enter a context with an instance of the API client
with datadog_api_client.v1.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = metrics_api.MetricsApi(api_client)
    metric_name = "metric_name_example" # str | Name of the metric for which to edit metadata.
    body = MetricMetadata(
        description="description_example",
        integration="integration_example",
        per_unit="second",
        short_name="short_name_example",
        statsd_interval=1,
        type="count",
        unit="byte",
    ) # MetricMetadata | New metadata.

    # example passing only required values which don't have defaults set
    try:
        # Edit metric metadata
        api_response = api_instance.update_metric_metadata(metric_name, body)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->update_metric_metadata: %s\n" % e)
# load the gem
require 'datadog_api_client/v1'
# setup authorization
DatadogAPIClient::V1.configure do |config|
  # Configure API key authorization: apiKeyAuth
  config.api_key['apiKeyAuth'] = ENV["DD_CLIENT_API_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['apiKeyAuth'] = 'Bearer'

  # Configure API key authorization: appKeyAuth
  config.api_key['appKeyAuth'] = ENV["DD_CLIENT_APP_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['appKeyAuth'] = 'Bearer'
end

api_instance = DatadogAPIClient::V1::MetricsApi.new
metric_name = 'metric_name_example' # String | Name of the metric for which to edit metadata.
body = DatadogAPIClient::V1::MetricMetadata.new # MetricMetadata | New metadata.

begin
  #Edit metric metadata
  result = api_instance.update_metric_metadata(metric_name, body)
  p result
rescue DatadogAPIClient::V1::ApiError => e
  puts "Exception when calling MetricsApi->update_metric_metadata: #{e}"
end

Récupérer la liste des métriques actives

GET https://api.datadoghq.eu/api/v1/metricshttps://api.datadoghq.com/api/v1/metrics

Présentation

Récupérez la liste des métriques transmises entre une date précise et maintenant.

Arguments

Chaînes de requête

Nom

Type

Description

from [required]

integer

Seconds since the Unix epoch.

host

string

Hostname for filtering the list of metrics returned. If set, metrics retrieved are those with the corresponding hostname tag.

Réponse

OK

Object listing all metric names stored by Datadog since a given time.

Expand All

Champ

Type

Description

from

string

Time when the metrics were active, seconds since the Unix epoch.

metrics

[string]

List of metric names.

{
  "from": "string",
  "metrics": []
}

Bad Request

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Forbidden

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        # Required query arguments
export from="CHANGE_ME"
# Curl command curl -X GET "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/metrics?from=${from}" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}"
package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },
        },
    )

    from := int64(789) // int64 | Seconds since the Unix epoch.
    host := "host_example" // string | Hostname for filtering the list of metrics returned. If set, metrics retrieved are those with the corresponding hostname tag. (optional)

    configuration := datadog.NewConfiguration()

    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.ListActiveMetrics(ctx).From(from).Host(host).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.ListActiveMetrics``: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `ListActiveMetrics`: MetricsListResponse
    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.ListActiveMetrics`: %v\n", resp)
}
// Import classes:
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.auth.*;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.MetricsApi;

public class Example {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // Configure the Datadog site to send API calls to
        HashMap<String, String> serverVariables = new HashMap<String, String>();
        String site = System.getenv("DD_SITE");
        if (site != null) {
            serverVariables.put("site", site);
            defaultClient.setServerVariables(serverVariables);
        }
        // Configure API key authorization: 
        HashMap<String, String> secrets = new HashMap<String, String>();
        secrets.put("apiKeyAuth", System.getenv("DD_CLIENT_API_KEY"));
        secrets.put("appKeyAuth", System.getenv("DD_CLIENT_APP_KEY"));
        defaultClient.configureApiKeys(secrets);

        MetricsApi apiInstance = new MetricsApi(defaultClient);
        Long from = 56L; // Long | Seconds since the Unix epoch.
        String host = "host_example"; // String | Hostname for filtering the list of metrics returned. If set, metrics retrieved are those with the corresponding hostname tag.
        try {
            MetricsListResponse result = apiInstance.listActiveMetrics()
                .from(from)
                .host(host)
                .execute();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling MetricsApi#listActiveMetrics");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}
from datadog import initialize, api
import time

options = {
    'api_key': '<DATADOG_API_KEY>',
    'app_key': '<DATADOG_APPLICATION_KEY>'
}

initialize(**options)

# Taking the last 24hours
from_time = int(time.time()) - 60 * 60 * 24 * 1

result = api.Metric.list(from_time)

print(result)
import os
from dateutil.parser import parse as dateutil_parser
import datadog_api_client.v1
from datadog_api_client.v1.api import metrics_api
from datadog_api_client.v1.models import *
from pprint import pprint
# Defining the host is optional and defaults to https://api.datadoghq.com
# See configuration.py for a list of all supported configuration parameters.
configuration = datadog_api_client.v1.Configuration(
    host = "https://api.datadoghq.com"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure API key authorization: apiKeyAuth
configuration.api_key['apiKeyAuth'] = os.getenv('DD_CLIENT_API_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['apiKeyAuth'] = 'Bearer'

# Configure API key authorization: appKeyAuth
configuration.api_key['appKeyAuth'] = os.getenv('DD_CLIENT_APP_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['appKeyAuth'] = 'Bearer'

# Enter a context with an instance of the API client
with datadog_api_client.v1.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = metrics_api.MetricsApi(api_client)
    _from = 1 # int | Seconds since the Unix epoch.
    host = "host_example" # str | Hostname for filtering the list of metrics returned. If set, metrics retrieved are those with the corresponding hostname tag. (optional)

    # example passing only required values which don't have defaults set
    try:
        # Get active metrics list
        api_response = api_instance.list_active_metrics(_from)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->list_active_metrics: %s\n" % e)

    # example passing only required values which don't have defaults set
    # and optional values
    try:
        # Get active metrics list
        api_response = api_instance.list_active_metrics(_from, host=host)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->list_active_metrics: %s\n" % e)
# load the gem
require 'datadog_api_client/v1'
# setup authorization
DatadogAPIClient::V1.configure do |config|
  # Configure API key authorization: apiKeyAuth
  config.api_key['apiKeyAuth'] = ENV["DD_CLIENT_API_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['apiKeyAuth'] = 'Bearer'

  # Configure API key authorization: appKeyAuth
  config.api_key['appKeyAuth'] = ENV["DD_CLIENT_APP_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['appKeyAuth'] = 'Bearer'
end

api_instance = DatadogAPIClient::V1::MetricsApi.new
from = 56 # Integer | Seconds since the Unix epoch.
opts = {
  host: 'host_example' # String | Hostname for filtering the list of metrics returned. If set, metrics retrieved are those with the corresponding hostname tag.
}

begin
  #Get active metrics list
  result = api_instance.list_active_metrics(from, opts)
  p result
rescue DatadogAPIClient::V1::ApiError => e
  puts "Exception when calling MetricsApi->list_active_metrics: #{e}"
end

Récupérer les métadonnées d'une métrique

GET https://api.datadoghq.eu/api/v1/metrics/{metric_name}https://api.datadoghq.com/api/v1/metrics/{metric_name}

Présentation

Récupérez les métadonnées d’une métrique spécifique.

Arguments

Paramètres du chemin

Nom

Type

Description

metric_name [required]

string

Name of the metric for which to get metadata.

Réponse

OK

Object with all metric related metadata.

Expand All

Champ

Type

Description

description

string

Metric description.

integration

string

Name of the integration that sent the metric if applicable.

per_unit

string

Per unit of the metric such as second in bytes per second.

short_name

string

A more human-readable and abbreviated version of the metric name.

statsd_interval

int64

StatsD flush interval of the metric in seconds if applicable.

type

string

Metric type such as gauge or rate.

unit

string

Primary unit of the metric such as byte or operation.

{
  "description": "string",
  "integration": "string",
  "per_unit": "second",
  "short_name": "string",
  "statsd_interval": "integer",
  "type": "count",
  "unit": "byte"
}

Forbidden

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Not Found

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        # Path parameters
export metric_name="CHANGE_ME"
# Curl command curl -X GET "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/metrics/${metric_name}" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}"
package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },
        },
    )

    metricName := "metricName_example" // string | Name of the metric for which to get metadata.

    configuration := datadog.NewConfiguration()

    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.GetMetricMetadata(ctx, metricName).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.GetMetricMetadata``: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `GetMetricMetadata`: MetricMetadata
    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.GetMetricMetadata`: %v\n", resp)
}
// Import classes:
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.auth.*;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.MetricsApi;

public class Example {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // Configure the Datadog site to send API calls to
        HashMap<String, String> serverVariables = new HashMap<String, String>();
        String site = System.getenv("DD_SITE");
        if (site != null) {
            serverVariables.put("site", site);
            defaultClient.setServerVariables(serverVariables);
        }
        // Configure API key authorization: 
        HashMap<String, String> secrets = new HashMap<String, String>();
        secrets.put("apiKeyAuth", System.getenv("DD_CLIENT_API_KEY"));
        secrets.put("appKeyAuth", System.getenv("DD_CLIENT_APP_KEY"));
        defaultClient.configureApiKeys(secrets);

        MetricsApi apiInstance = new MetricsApi(defaultClient);
        String metricName = "metricName_example"; // String | Name of the metric for which to get metadata.
        try {
            MetricMetadata result = apiInstance.getMetricMetadata(metricName)
                .execute();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling MetricsApi#getMetricMetadata");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}
from datadog import initialize, api

options = {
    'api_key': '<DATADOG_API_KEY>',
    'app_key': '<DATADOG_APPLICATION_KEY>'
}

initialize(**options)

metric = 'system.cpu.idle'

api.Metadata.get(metric_name=metric)
import os
from dateutil.parser import parse as dateutil_parser
import datadog_api_client.v1
from datadog_api_client.v1.api import metrics_api
from datadog_api_client.v1.models import *
from pprint import pprint
# Defining the host is optional and defaults to https://api.datadoghq.com
# See configuration.py for a list of all supported configuration parameters.
configuration = datadog_api_client.v1.Configuration(
    host = "https://api.datadoghq.com"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure API key authorization: apiKeyAuth
configuration.api_key['apiKeyAuth'] = os.getenv('DD_CLIENT_API_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['apiKeyAuth'] = 'Bearer'

# Configure API key authorization: appKeyAuth
configuration.api_key['appKeyAuth'] = os.getenv('DD_CLIENT_APP_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['appKeyAuth'] = 'Bearer'

# Enter a context with an instance of the API client
with datadog_api_client.v1.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = metrics_api.MetricsApi(api_client)
    metric_name = "metric_name_example" # str | Name of the metric for which to get metadata.

    # example passing only required values which don't have defaults set
    try:
        # Get metric metadata
        api_response = api_instance.get_metric_metadata(metric_name)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->get_metric_metadata: %s\n" % e)
require 'rubygems'
require 'dogapi'

api_key = '<DATADOG_API_KEY>'
app_key = '<DATADOG_APPLICATION_KEY>'

dog = Dogapi::Client.new(api_key, app_key)

# Get metadata on metric
result = dog.get_metadata('system.net.bytes_sent')
# load the gem
require 'datadog_api_client/v1'
# setup authorization
DatadogAPIClient::V1.configure do |config|
  # Configure API key authorization: apiKeyAuth
  config.api_key['apiKeyAuth'] = ENV["DD_CLIENT_API_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['apiKeyAuth'] = 'Bearer'

  # Configure API key authorization: appKeyAuth
  config.api_key['appKeyAuth'] = ENV["DD_CLIENT_APP_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['appKeyAuth'] = 'Bearer'
end

api_instance = DatadogAPIClient::V1::MetricsApi.new
metric_name = 'metric_name_example' # String | Name of the metric for which to get metadata.

begin
  #Get metric metadata
  result = api_instance.get_metric_metadata(metric_name)
  p result
rescue DatadogAPIClient::V1::ApiError => e
  puts "Exception when calling MetricsApi->get_metric_metadata: #{e}"
end

Interroger les points de séries temporelles

GET https://api.datadoghq.eu/api/v1/queryhttps://api.datadoghq.com/api/v1/query

Présentation

Interrogez les points de séries temporelles.

Arguments

Chaînes de requête

Nom

Type

Description

from [required]

integer

Start of the queried time period, seconds since the Unix epoch.

to [required]

integer

End of the queried time period, seconds since the Unix epoch.

query [required]

string

Query string.

Réponse

OK

Response Object that includes your query and the list of metrics retrieved.

Expand All

Champ

Type

Description

error

string

Message indicating the errors if status is not ok.

from_date

int64

Start of requested time window, milliseconds since Unix epoch.

group_by

[string]

List of tag keys on which to group.

message

string

Message indicating success if status is ok.

query

string

Query string

res_type

string

Type of response.

series

[object]

List of timeseries queried.

aggr

string

Aggregation type.

display_name

string

Display name of the metric.

end

int64

End of the time window, milliseconds since Unix epoch.

expression

string

Metric expression.

interval

int64

Number of seconds between data samples.

length

int64

Number of data samples.

metric

string

Metric name.

pointlist

[array]

List of points of the time series.

scope

string

Metric scope, comma separated list of tags.

start

int64

Start of the time window, milliseconds since Unix epoch.

unit

[object]

Detailed information about the metric unit. First element describes the "primary unit" (for example, bytes in bytes per second), second describes the "per unit" (for example, second in bytes per second).

family

string

Unit family, allows for conversion between units of the same family, for scaling.

name

string

Unit name

plural

string

Plural form of the unit name.

scale_factor

double

Factor for scaling between units of the same family.

short_name

string

Abbreviation of the unit.

status

string

Status of the query.

to_date

int64

End of requested time window, milliseconds since Unix epoch.

{
  "error": "string",
  "from_date": "integer",
  "group_by": [],
  "message": "string",
  "query": "string",
  "res_type": "time_series",
  "series": [
    {
      "aggr": "avg",
      "display_name": "system.cpu.idle",
      "end": "integer",
      "expression": "system.cpu.idle{host:foo,env:test}",
      "interval": "integer",
      "length": "integer",
      "metric": "system.cpu.idle",
      "pointlist": [
        1575317847,
        0.5
      ],
      "scope": "host:foo,env:test",
      "start": "integer",
      "unit": [
        {
          "family": "time",
          "name": "minute",
          "plural": "minutes",
          "scale_factor": 60,
          "short_name": "min"
        }
      ]
    }
  ],
  "status": "ok",
  "to_date": "integer"
}

Bad Request

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Forbidden

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        # Required query arguments
export from="CHANGE_ME"
export to="CHANGE_ME"
export query="CHANGE_ME"
# Curl command curl -X GET "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/query?from=${from}&to=${to}&query=${query}" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}"
package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },
        },
    )

    from := int64(789) // int64 | Start of the queried time period, seconds since the Unix epoch.
    to := int64(789) // int64 | End of the queried time period, seconds since the Unix epoch.
    query := "query_example" // string | Query string.

    configuration := datadog.NewConfiguration()

    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.QueryMetrics(ctx).From(from).To(to).Query(query).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.QueryMetrics``: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `QueryMetrics`: MetricsQueryResponse
    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.QueryMetrics`: %v\n", resp)
}
// Import classes:
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.auth.*;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.MetricsApi;

public class Example {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // Configure the Datadog site to send API calls to
        HashMap<String, String> serverVariables = new HashMap<String, String>();
        String site = System.getenv("DD_SITE");
        if (site != null) {
            serverVariables.put("site", site);
            defaultClient.setServerVariables(serverVariables);
        }
        // Configure API key authorization: 
        HashMap<String, String> secrets = new HashMap<String, String>();
        secrets.put("apiKeyAuth", System.getenv("DD_CLIENT_API_KEY"));
        secrets.put("appKeyAuth", System.getenv("DD_CLIENT_APP_KEY"));
        defaultClient.configureApiKeys(secrets);

        MetricsApi apiInstance = new MetricsApi(defaultClient);
        Long from = 56L; // Long | Start of the queried time period, seconds since the Unix epoch.
        Long to = 56L; // Long | End of the queried time period, seconds since the Unix epoch.
        String query = "query_example"; // String | Query string.
        try {
            MetricsQueryResponse result = apiInstance.queryMetrics()
                .from(from)
                .to(to)
                .query(query)
                .execute();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling MetricsApi#queryMetrics");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}
from datadog import initialize, api
import time

options = {
    'api_key': '<DATADOG_API_KEY>',
    'app_key': '<DATADOG_APPLICATION_KEY>'
}

initialize(**options)

now = int(time.time())

query = 'system.cpu.idle{*}by{host}'
print(api.Metric.query(start=now - 3600, end=now, query=query))
import os
from dateutil.parser import parse as dateutil_parser
import datadog_api_client.v1
from datadog_api_client.v1.api import metrics_api
from datadog_api_client.v1.models import *
from pprint import pprint
# Defining the host is optional and defaults to https://api.datadoghq.com
# See configuration.py for a list of all supported configuration parameters.
configuration = datadog_api_client.v1.Configuration(
    host = "https://api.datadoghq.com"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure API key authorization: apiKeyAuth
configuration.api_key['apiKeyAuth'] = os.getenv('DD_CLIENT_API_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['apiKeyAuth'] = 'Bearer'

# Configure API key authorization: appKeyAuth
configuration.api_key['appKeyAuth'] = os.getenv('DD_CLIENT_APP_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['appKeyAuth'] = 'Bearer'

# Enter a context with an instance of the API client
with datadog_api_client.v1.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = metrics_api.MetricsApi(api_client)
    _from = 1 # int | Start of the queried time period, seconds since the Unix epoch.
    to = 1 # int | End of the queried time period, seconds since the Unix epoch.
    query = "query_example" # str | Query string.

    # example passing only required values which don't have defaults set
    try:
        # Query timeseries points
        api_response = api_instance.query_metrics(_from, to, query)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->query_metrics: %s\n" % e)
require 'rubygems'
require 'dogapi'

api_key = '<DATADOG_API_KEY>'
app_key = '<DATADOG_APPLICATION_KEY>'

dog = Dogapi::Client.new(api_key, app_key)

# Get points from the last hour
from = Time.now - 3600
to = Time.now
query = 'system.cpu.idle{*}by{host}'

dog.get_points(query, from, to)
# load the gem
require 'datadog_api_client/v1'
# setup authorization
DatadogAPIClient::V1.configure do |config|
  # Configure API key authorization: apiKeyAuth
  config.api_key['apiKeyAuth'] = ENV["DD_CLIENT_API_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['apiKeyAuth'] = 'Bearer'

  # Configure API key authorization: appKeyAuth
  config.api_key['appKeyAuth'] = ENV["DD_CLIENT_APP_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['appKeyAuth'] = 'Bearer'
end

api_instance = DatadogAPIClient::V1::MetricsApi.new
from = 56 # Integer | Start of the queried time period, seconds since the Unix epoch.
to = 56 # Integer | End of the queried time period, seconds since the Unix epoch.
query = 'query_example' # String | Query string.

begin
  #Query timeseries points
  result = api_instance.query_metrics(from, to, query)
  p result
rescue DatadogAPIClient::V1::ApiError => e
  puts "Exception when calling MetricsApi->query_metrics: #{e}"
end

Rechercher des métriques

GET https://api.datadoghq.eu/api/v1/searchhttps://api.datadoghq.com/api/v1/search

Présentation

Recherchez des métriques parmi celles recueillies au cours des dernières 24 heures dans Datadog.

Arguments

Chaînes de requête

Nom

Type

Description

q [required]

string

Query string to search metrics upon. Must be prefixed with metrics:.

Réponse

OK

Object containing the list of metrics matching the search query.

Expand All

Champ

Type

Description

results

object

Search result.

metrics

[string]

List of metrics that match the search query.

{
  "results": {
    "metrics": []
  }
}

Bad Request

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Forbidden

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        # Required query arguments
export q="CHANGE_ME"
# Curl command curl -X GET "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/search?q=${q}" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_CLIENT_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_CLIENT_APP_KEY}"
package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },
        },
    )

    q := "q_example" // string | Query string to search metrics upon. Must be prefixed with `metrics:`.

    configuration := datadog.NewConfiguration()

    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.ListMetrics(ctx).Q(q).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.ListMetrics``: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `ListMetrics`: MetricSearchResponse
    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.ListMetrics`: %v\n", resp)
}
// Import classes:
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.auth.*;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.MetricsApi;

public class Example {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // Configure the Datadog site to send API calls to
        HashMap<String, String> serverVariables = new HashMap<String, String>();
        String site = System.getenv("DD_SITE");
        if (site != null) {
            serverVariables.put("site", site);
            defaultClient.setServerVariables(serverVariables);
        }
        // Configure API key authorization: 
        HashMap<String, String> secrets = new HashMap<String, String>();
        secrets.put("apiKeyAuth", System.getenv("DD_CLIENT_API_KEY"));
        secrets.put("appKeyAuth", System.getenv("DD_CLIENT_APP_KEY"));
        defaultClient.configureApiKeys(secrets);

        MetricsApi apiInstance = new MetricsApi(defaultClient);
        String q = "q_example"; // String | Query string to search metrics upon. Must be prefixed with `metrics:`.
        try {
            MetricSearchResponse result = apiInstance.listMetrics()
                .q(q)
                .execute();
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling MetricsApi#listMetrics");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
    }
}
import os
from dateutil.parser import parse as dateutil_parser
import datadog_api_client.v1
from datadog_api_client.v1.api import metrics_api
from datadog_api_client.v1.models import *
from pprint import pprint
# Defining the host is optional and defaults to https://api.datadoghq.com
# See configuration.py for a list of all supported configuration parameters.
configuration = datadog_api_client.v1.Configuration(
    host = "https://api.datadoghq.com"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure API key authorization: apiKeyAuth
configuration.api_key['apiKeyAuth'] = os.getenv('DD_CLIENT_API_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['apiKeyAuth'] = 'Bearer'

# Configure API key authorization: appKeyAuth
configuration.api_key['appKeyAuth'] = os.getenv('DD_CLIENT_APP_KEY')

# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['appKeyAuth'] = 'Bearer'

# Enter a context with an instance of the API client
with datadog_api_client.v1.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = metrics_api.MetricsApi(api_client)
    q = "q_example" # str | Query string to search metrics upon. Must be prefixed with `metrics:`.

    # example passing only required values which don't have defaults set
    try:
        # Search metrics
        api_response = api_instance.list_metrics(q)
        pprint(api_response)
    except datadog_api_client.v1.ApiException as e:
        print("Exception when calling MetricsApi->list_metrics: %s\n" % e)
require 'rubygems'
require 'dogapi'

api_key = '<DATADOG_API_KEY>'
app_key = '<DATADOG_APPLICATION_KEY>'

dog = Dogapi::Client.new(api_key, app_key)

dog.search("metrics:test")
# load the gem
require 'datadog_api_client/v1'
# setup authorization
DatadogAPIClient::V1.configure do |config|
  # Configure API key authorization: apiKeyAuth
  config.api_key['apiKeyAuth'] = ENV["DD_CLIENT_API_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['apiKeyAuth'] = 'Bearer'

  # Configure API key authorization: appKeyAuth
  config.api_key['appKeyAuth'] = ENV["DD_CLIENT_APP_KEY"]
  # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
  #config.api_key_prefix['appKeyAuth'] = 'Bearer'
end

api_instance = DatadogAPIClient::V1::MetricsApi.new
q = 'q_example' # String | Query string to search metrics upon. Must be prefixed with `metrics:`.

begin
  #Search metrics
  result = api_instance.list_metrics(q)
  p result
rescue DatadogAPIClient::V1::ApiError => e
  puts "Exception when calling MetricsApi->list_metrics: #{e}"
end

Envoyer des métriques

POST https://api.datadoghq.eu/api/v1/serieshttps://api.datadoghq.com/api/v1/series

Présentation

L’endpoint de métrique vous permet d’envoyer des données de séries temporelles afin de les représenter graphiquement sur les dashboards de Datadog. La limite de taille des charges utiles compressées est de 3,2 mégaoctets (3 200 000), tandis que celle des charges utiles non compressées est de 62 mégaoctets (62 914 560).

Si vous envoyez directement des métriques à l’API Datadog sans passer par DogStatsD, attendez-vous à :

  • 64 bits pour le timestamp
  • 64 bits pour la valeur
  • 20 octets pour les noms de métriques
  • 50 octets pour les séries temporelles
  • La charge utile totale pèse environ 100 octets. Cependant, avec l’API DogStatsD, cette charge est compressée afin de réduire son poids.

Requête

Body Data (required)

Expand All

Champ

Type

Description

series

[object]

A list of time series to submit to Datadog.

host

string

The name of the host that produced the metric.

interval

int64

If the type of the metric is rate or count, define the corresponding interval.

metric [required]

string

The name of the timeseries.

points [required]

[array]

Points relating to a metric. All points must be tuples with timestamp and a scalar value (cannot be a string). Timestamps cannot be more than ten minutes in the future or more than one hour in the past.

tags

[string]

A list of tags associated with the metric.

type

string

The type of the metric either count, gauge, or rate.

{
  "series": [
    {
      "host": "test.example.com",
      "interval": 20,
      "metric": "system.load.1",
      "points": [
        [
          1575317847,
          0.5
        ]
      ],
      "tags": [
        "environment:test"
      ],
      "type": "rate"
    }
  ]
}

Réponse

Payload accepted

The payload accepted for intake.

Expand All

Champ

Type

Description

status

string

The status of the intake payload.

{
  "status": "ok"
}

Bad Request

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Authentication error

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Request timeout

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Payload too large

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

{
  "errors": [
    "Bad Request"
  ]
}

Exemple de code


                                        ## Dynamic Points
# TODO.
# Template variables
export NOW="$(date +%s)"
# Curl command curl -X POST "https://api.datadoghq.eu"https://api.datadoghq.com/api/v1/series?api_key=${DD_CLIENT_API_KEY}" \ -H "Content-Type: application/json" \ -d @- << EOF { "series": [ { "metric": "system.load.1", "points": [ [ "${NOW}", "1234.5" ] ] } ] } EOF
from datadog import initialize, api
import time

options = {
    'api_key': '<DATADOG_API_KEY>'
    ## EU costumers need to define 'api_host' as below
    #'api_host': 'https://api.datadoghq.eu/'
}

initialize(**options)

now = time.time()
future_10s = now + 10

# Submit a single point with a timestamp of `now`
api.Metric.send(metric='page.views', points=1000)

# Submit a point with a timestamp (must be current)
api.Metric.send(metric='my.pair', points=(now, 15))

# Submit multiple points.
api.Metric.send(
    metric='my.series',
    points=[
        (now, 15),
        (future_10s, 16)
    ]
)

# Submit a point with a host and tags.
api.Metric.send(
    metric='my.series',
    points=100,
    host="myhost.example.com",
    tags=["version:1"]
)

# Submit multiple metrics
api.Metric.send([{
    'metric': 'my.series',
    'points': 15
}, {
    'metric': 'my1.series',
    'points': 16
}])
require 'rubygems'
require 'dogapi'

api_key = '<DATADOG_API_KEY>'

dog = Dogapi::Client.new(api_key)

# Submit one metric value.
dog.emit_point('some.metric.name', 50.0, :host => "my_host.example.com")

# Submit multiple metric values
points = [
    [Time.now, 0],
    [Time.now + 10, 10.0],
    [Time.now + 20, 20.0]
]
dog.emit_points('some.metric.name', points, :tags => ["version:1"])

# Emit differents metrics in a single request to be more efficient
dog.batch_metrics do
  dog.emit_point('test.api.test_metric',10)
  dog.emit_point('test.api.this_other_metric', 1)
end