Monitores

Los monitores te permiten observar una métrica o un check que te interese y notificar a tu equipo cuando se supera un umbral definido.

Para obtener más información, consulta la creación de monitores.

POST https://api.ap1.datadoghq.com/api/v1/monitorhttps://api.datadoghq.eu/api/v1/monitorhttps://api.ddog-gov.com/api/v1/monitorhttps://api.datadoghq.com/api/v1/monitorhttps://api.us3.datadoghq.com/api/v1/monitorhttps://api.us5.datadoghq.com/api/v1/monitor

Información general

Crea un monitor utilizando las opciones especificadas.

Tipos de monitores

Tipo de monitor elegido de:

  • anomalía: query alert
  • APM: query alert or trace-analytics alert
  • compuesto: composite
  • personalizado: service check
  • previsión: query alert
  • host: service check
  • integración: query alert or service check
  • proceso en directo: process alert
  • logs: log alert
  • métric:a query alert
  • red: service check
  • outlier: query alert
  • proceso: service check
  • rum: rum alert
  • SLO: slo alert
  • watchdog: event-v2 alert
  • evento-v2: event-v2 alert
  • auditoría: audit alert
  • seguimiento de errores: error-tracking alert
  • monitorización de bases de datos: database-monitoring alert
  • rendimiento de redes: network-performance alert
  • coste de la nube: cost alert

Notas:

  • Los monitores Synthetic se crean mediante la API Synthetics. Para obtener más información, consulta la documentación de la API Synthetics.
  • Los monitores de logs requieren una clave de aplicación sin contexto.

Tipos de consultas

Consulta de alertas de métricas

Ejemplo: time_aggr(time_window):space_aggr:metric{tags} [by {key}] operator #

  • time_aggr: avg, sum, max, min, change o pct_change
  • time_window: last_#m (con # entre 1 y 10080 dependiendo del tipo de monitor) o last_#h(con# entre 1 y 168 dependiendo del tipo de monitor) o last_1d o last_1w
  • space_aggr: avg, sum, min, or max
  • tags: una o más etiquetas (separadas por comas) o *
  • key: a ‘key’ en sintaxis de etiqueta key:value; define una alerta individual para cada etiqueta del grupo (alertas múltiples)
  • operator: <, <=, >, >=, ==, or !=
  • #: número entero o decimal utilizado para definir el umbral

Si estás utilizando el agregador de tiempo _change_ or _pct_change_, utiliza change_aggr(time_aggr(time_window) en su lugar, timeshift):space_aggr:metric{tags} [by {key}] operator # con:

  • change_aggr change, pct_change
  • time_aggr avg, sum, max, min Más información
  • time_window last_#m (entre 1 y 2880 dependiendo del tipo de monitor), last_#h (entre 1 y 48 dependiendo del tipo de monitor) o last_#d (1 or 2)
  • timeshift #m_ago (5, 10, 15 o 30), #h_ago (1, 2 o 4) o 1d_ago

Utiliza esto para crear un monitor de outliers con la siguiente consulta: avg(last_30m):outliers(avg:system.cpu.user{role:es-events-data} por {host}, 'dbscan', 7) > 0

Consulta de checks de servicio

Ejemplo: "check".over(tags).last(count).by(group).count_by_status()

  • check nombre del check, por ejemplo datadog.agent.up
  • tags una o más etiquetas entre comillas (separadas por comas) o “*”. por ejemplo: .over("env:prod", "role:db"); over no puede estar vacío.
  • count debe ser mayor o igual que tu umbral máximo (definido en las opciones). Se limita a 100. Por ejemplo, si definiste la notificación de estados 1 crítico, 3 ok y 2 advertencia, count` debería ser al menos 3.
  • group debe especificarse para monitores de checks. La agrupación por cada check ya es explícitamente conocida en algunos checks de servicio. Por ejemplo, los monitores de la integración Postgres están etiquetados como db, host y port, y los monitores de redes, como host, instance y url. Para obtener más información, consulta la documentación Checks de servicios.
Consulta de alertas de eventos

Nota: La Consulta de alertas de eventos ha sido sustituida por la Consulta de alertas de eventos V2. Para obtener más información, consulta la guía Migración de eventos.

Consulta de alertas de eventos V2

Ejemplo: events(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query Consulta de búsqueda que sigue la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admiten count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o el nombre de faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
Consulta de alertas de procesos

Ejemplo: processes(search).over(tags).rollup('count').last(timeframe) operator #

  • search Cadena de búsqueda de texto libre para consultar procesos. Resultados del emparejamiento de procesos coincidentes en la página Procesos en directo.
  • tags una o más etiquetas (separadas por comas)
  • timeframe periodo de tiempo de los recuentos. Ejemplos: 10m, 4h. Periodos de tiempo compatibles: s, m, h, d
  • operator <, <=, >, >=, == o !=
  • # número entero o decimal utilizado para definir el umbral
Consulta de alertas de logs

Ejemplo: logs(query).index(index_name).rollup(rollup_method[, measure]).last(time_window) operator #

  • query Consulta de búsqueda que sigue la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admiten count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o el nombre de faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
Consulta compuesta

Ejemplo: 12345 && 67890, donde 12345 y 67890 son los ID de los monitores no compuestos

  • name [required, default = dynamic, based on query]: Nombre de la alerta.
  • message [required, default = dynamic, based on query]: Mensaje a incluir con las notificaciones de este monitor. Se pueden enviar notificaciones por correo electrónico a usuarios específicos utilizando la misma notación ‘@username’ que en los eventos.
  • tags [optional, default = empty list]: Lista de etiquetas a asociar con tu monitor. Al obtener detalles de monitores a través de la API, utiliza el argumento monitor_tags para filtrar los resultados por esas etiquetas. Sólo está disponible a través de la API y no es visible ni editable en la interfaz de usuario de Datadog.
Consulta de alertas de SLOs

Ejemplo: error_budget("slo_id").over("time_window") operator #

  • slo_id: El ID alfanumérico del SLO para el que configuras la alerta.
  • time_window: La ventana de tiempo del destino del SLO sobre el que quieres generar alertas. Opciones válidas: 7d, 30d, 90d.
  • operator: >= or >
Consulta de alertas de auditorías

Ejemplo: audits(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
Consulta de alertas de pipelines CI

Ejemplo: ci-pipelines(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
Consulta de alertas de tests CI

Ejemplo: ci-tests(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
Consulta de alertas de seguimiento de errores

Ejemplo (RUM): error-tracking-rum(query).rollup(rollup_method[, measure]).last(time_window) operator # Ejemplo (Trazas (traces) de APM): error-tracking-traces(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.

Consulta de alertas de la monitorización de bases de datos

Ejemplo: database-monitoring(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.

Consulta de alertas de rendimiento de redes

Ejemplo: network-performance(query).rollup(rollup_method[, measure]).last(time_window) operator #

  • query La consulta de búsqueda que utiliza la sintaxis de búsqueda de logs.
  • rollup_method Las estadísticas roll-up method - admite count, avg y cardinality.
  • measure Para avg y cardinality rollup_method - especifica la medida o nombre de la faceta que quieres utilizar.
  • time_window #m (entre 1 y 2880), #h (entre 1 y 48).
  • operator <, <=, >, >=, ==, or !=.
  • # número entero o decimal utilizado para definir el umbral.
This endpoint requires the monitors_write permission.

OAuth apps require the monitors_write authorization scope to access this endpoint.

Solicitud

Body Data (required)

Crea el cuerpo de una solicitud de monitor.

Expand All

Campo

Tipo

Descripción

created

date-time

Timestamp of the monitor creation.

creator

object

Object describing the creator of the shared element.

email

string

Email of the creator.

handle

string

Handle of the creator.

name

string

Name of the creator.

deleted

date-time

Whether or not the monitor is deleted. (Always null)

id

int64

ID of this monitor.

matching_downtimes

[object]

A list of active v1 downtimes that match this monitor.

end

int64

POSIX timestamp to end the downtime.

id [required]

int64

The downtime ID.

scope

[string]

The scope(s) to which the downtime applies. Must be in key:value format. For example, host:app2. Provide multiple scopes as a comma-separated list like env:dev,env:prod. The resulting downtime applies to sources that matches ALL provided scopes (env:dev AND env:prod).

start

int64

POSIX timestamp to start the downtime.

message

string

A message to include with notifications for this monitor.

modified

date-time

Last timestamp when the monitor was edited.

multi

boolean

Whether or not the monitor is broken down on different groups.

name

string

The monitor name.

options

object

List of options associated with your monitor.

aggregation

object

Type of aggregation performed in the monitor query.

group_by

string

Group to break down the monitor on.

metric

string

Metric name used in the monitor.

type

string

Metric type used in the monitor.

device_ids

[string]

DEPRECATED: IDs of the device the Synthetics monitor is running on.

enable_logs_sample

boolean

Whether or not to send a log sample when the log monitor triggers.

enable_samples

boolean

Whether or not to send a list of samples when the monitor triggers. This is only used by CI Test and Pipeline monitors.

escalation_message

string

We recommend using the is_renotify, block in the original message instead. A message to include with a re-notification. Supports the @username notification we allow elsewhere. Not applicable if renotify_interval is None.

evaluation_delay

int64

Time (in seconds) to delay evaluation, as a non-negative integer. For example, if the value is set to 300 (5min), the timeframe is set to last_5m and the time is 7:00, the monitor evaluates data from 6:50 to 6:55. This is useful for AWS CloudWatch and other backfilled metrics to ensure the monitor always has data during evaluation.

group_retention_duration

string

The time span after which groups with missing data are dropped from the monitor state. The minimum value is one hour, and the maximum value is 72 hours. Example values are: "60m", "1h", and "2d". This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors.

groupby_simple_monitor

boolean

DEPRECATED: Whether the log alert monitor triggers a single alert or multiple alerts when any group breaches a threshold. Use notify_by instead.

include_tags

boolean

A Boolean indicating whether notifications from this monitor automatically inserts its triggering tags into the title.

Examples

  • If True, [Triggered on {host:h1}] Monitor Title
  • If False, [Triggered] Monitor Title

default: true

locked

boolean

DEPRECATED: Whether or not the monitor is locked (only editable by creator and admins). Use restricted_roles instead.

min_failure_duration

int64

How long the test should be in failure before alerting (integer, number of seconds, max 7200).

min_location_failed

int64

The minimum number of locations in failure at the same time during at least one moment in the min_failure_duration period (min_location_failed and min_failure_duration are part of the advanced alerting rules - integer, >= 1).

default: 1

new_group_delay

int64

Time (in seconds) to skip evaluations for new groups.

For example, this option can be used to skip evaluations for new hosts while they initialize.

Must be a non negative integer.

new_host_delay

int64

DEPRECATED: Time (in seconds) to allow a host to boot and applications to fully start before starting the evaluation of monitor results. Should be a non negative integer.

Use new_group_delay instead.

default: 300

no_data_timeframe

int64

The number of minutes before a monitor notifies after data stops reporting. Datadog recommends at least 2x the monitor timeframe for query alerts or 2 minutes for service checks. If omitted, 2x the evaluation timeframe is used for query alerts, and 24 hours is used for service checks.

notification_preset_name

enum

Toggles the display of additional content sent in the monitor notification. Allowed enum values: show_all,hide_query,hide_handles,hide_all

default: show_all

notify_audit

boolean

A Boolean indicating whether tagged users is notified on changes to this monitor.

notify_by

[string]

Controls what granularity a monitor alerts on. Only available for monitors with groupings. For instance, a monitor grouped by cluster, namespace, and pod can be configured to only notify on each new cluster violating the alert conditions by setting notify_by to ["cluster"]. Tags mentioned in notify_by must be a subset of the grouping tags in the query. For example, a query grouped by cluster and namespace cannot notify on region. Setting notify_by to [*] configures the monitor to notify as a simple-alert.

notify_no_data

boolean

A Boolean indicating whether this monitor notifies when data stops reporting. Defaults to false.

on_missing_data

enum

Controls how groups or monitors are treated if an evaluation does not return any data points. The default option results in different behavior depending on the monitor query type. For monitors using Count queries, an empty monitor evaluation is treated as 0 and is compared to the threshold conditions. For monitors using any query type other than Count, for example Gauge, Measure, or Rate, the monitor shows the last known status. This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors. Allowed enum values: default,show_no_data,show_and_notify_no_data,resolve

renotify_interval

int64

The number of minutes after the last notification before a monitor re-notifies on the current status. It only re-notifies if it’s not resolved.

renotify_occurrences

int64

The number of times re-notification messages should be sent on the current status at the provided re-notification interval.

renotify_statuses

[string]

The types of monitor statuses for which re-notification messages are sent. Default: null if renotify_interval is null. If renotify_interval is set, defaults to renotify on Alert and No Data.

require_full_window

boolean

A Boolean indicating whether this monitor needs a full window of data before it’s evaluated. We highly recommend you set this to false for sparse metrics, otherwise some evaluations are skipped. Default is false. This setting only applies to metric monitors.

scheduling_options

object

Configuration options for scheduling.

custom_schedule

object

Configuration options for the custom schedule. This feature is in private beta.

recurrences

[object]

Array of custom schedule recurrences.

rrule

string

Defines the recurrence rule (RRULE) for a given schedule.

start

string

Defines the start date and time of the recurring schedule.

timezone

string

Defines the timezone the schedule runs on.

evaluation_window

object

Configuration options for the evaluation window. If hour_starts is set, no other fields may be set. Otherwise, day_starts and month_starts must be set together.

day_starts

string

The time of the day at which a one day cumulative evaluation window starts. Must be defined in UTC time in HH:mm format.

hour_starts

int32

The minute of the hour at which a one hour cumulative evaluation window starts.

month_starts

int32

The day of the month at which a one month cumulative evaluation window starts.

silenced

object

DEPRECATED: Information about the downtime applied to the monitor. Only shows v1 downtimes.

<any-key>

int64

UTC epoch timestamp in seconds when the downtime for the group expires.

synthetics_check_id

string

DEPRECATED: ID of the corresponding Synthetic check.

threshold_windows

object

Alerting time window options.

recovery_window

string

Describes how long an anomalous metric must be normal before the alert recovers.

trigger_window

string

Describes how long a metric must be anomalous before an alert triggers.

thresholds

object

List of the different monitor threshold available.

critical

double

The monitor CRITICAL threshold.

critical_recovery

double

The monitor CRITICAL recovery threshold.

ok

double

The monitor OK threshold.

unknown

double

The monitor UNKNOWN threshold.

warning

double

The monitor WARNING threshold.

warning_recovery

double

The monitor WARNING recovery threshold.

timeout_h

int64

The number of hours of the monitor not reporting data before it automatically resolves from a triggered state. The minimum allowed value is 0 hours. The maximum allowed value is 24 hours.

variables

[ <oneOf>]

List of requests that can be used in the monitor query. This feature is currently in beta.

Option 1

object

A formula and functions events query.

compute [required]

object

Compute options.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

interval

int64

A time interval in milliseconds.

metric

string

Measurable attribute to compute.

data_source [required]

enum

Data source for event platform-based queries. Allowed enum values: rum,ci_pipelines,ci_tests,audit,events,logs,spans,database_queries,network

group_by

[object]

Group by options.

facet [required]

string

Event facet.

limit

int64

Number of groups to return.

sort

object

Options for sorting group by results.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

metric

string

Metric used for sorting group by results.

order

enum

Direction of sort. Allowed enum values: asc,desc

default: desc

indexes

[string]

An array of index names to query in the stream. Omit or use [] to query all indexes at once.

name [required]

string

Name of the query for use in formulas.

search

object

Search options.

query [required]

string

Events search string.

overall_state

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

priority

int64

Integer from 1 (high) to 5 (low) indicating alert severity.

query [required]

string

The monitor query.

restricted_roles

[string]

A list of unique role identifiers to define which roles are allowed to edit the monitor. The unique identifiers for all roles can be pulled from the Roles API and are located in the data.id field. Editing a monitor includes any updates to the monitor configuration, monitor deletion, and muting of the monitor for any amount of time. You can use the Restriction Policies API to manage write authorization for individual monitors by teams and users, in addition to roles.

state

object

Wrapper object with the different monitor states.

groups

object

Dictionary where the keys are groups (comma separated lists of tags) and the values are the list of groups your monitor is broken down on.

<any-key>

object

Monitor state for a single group.

last_nodata_ts

int64

Latest timestamp the monitor was in NO_DATA state.

last_notified_ts

int64

Latest timestamp of the notification sent for this monitor group.

last_resolved_ts

int64

Latest timestamp the monitor group was resolved.

last_triggered_ts

int64

Latest timestamp the monitor group triggered.

name

string

The name of the monitor.

status

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

tags

[string]

Tags associated to your monitor.

type [required]

enum

The type of the monitor. For more information about type, see the monitor options docs. Allowed enum values: composite,event alert,log alert,metric alert,process alert,query alert,rum alert,service check,synthetics alert,trace-analytics alert,slo alert,event-v2 alert,audit alert,ci-pipelines alert,ci-tests alert,error-tracking alert,database-monitoring alert,network-performance alert

{
  "name": "Example-Monitor",
  "type": "rum alert",
  "query": "formula(\"query2 / query1 * 100\").last(\"15m\") >= 0.8",
  "message": "some message Notify: @hipchat-channel",
  "tags": [
    "test:examplemonitor",
    "env:ci"
  ],
  "priority": 3,
  "options": {
    "thresholds": {
      "critical": 0.8
    },
    "variables": [
      {
        "data_source": "rum",
        "name": "query2",
        "search": {
          "query": ""
        },
        "indexes": [
          "*"
        ],
        "compute": {
          "aggregation": "count"
        },
        "group_by": []
      },
      {
        "data_source": "rum",
        "name": "query1",
        "search": {
          "query": "status:error"
        },
        "indexes": [
          "*"
        ],
        "compute": {
          "aggregation": "count"
        },
        "group_by": []
      }
    ]
  }
}
{
  "name": "Example-Monitor",
  "type": "ci-pipelines alert",
  "query": "formula(\"query1 / query2 * 100\").last(\"15m\") >= 0.8",
  "message": "some message Notify: @hipchat-channel",
  "tags": [
    "test:examplemonitor",
    "env:ci"
  ],
  "priority": 3,
  "options": {
    "thresholds": {
      "critical": 0.8
    },
    "variables": [
      {
        "data_source": "ci_pipelines",
        "name": "query1",
        "search": {
          "query": "@ci.status:error"
        },
        "indexes": [
          "*"
        ],
        "compute": {
          "aggregation": "count"
        },
        "group_by": []
      },
      {
        "data_source": "ci_pipelines",
        "name": "query2",
        "search": {
          "query": ""
        },
        "indexes": [
          "*"
        ],
        "compute": {
          "aggregation": "count"
        },
        "group_by": []
      }
    ]
  }
}
{
  "name": "Example-Monitor",
  "type": "ci-pipelines alert",
  "query": "ci-pipelines(\"ci_level:pipeline @git.branch:staging* @ci.status:error\").rollup(\"count\").by(\"@git.branch,@ci.pipeline.name\").last(\"5m\") >= 1",
  "message": "some message Notify: @hipchat-channel",
  "tags": [
    "test:examplemonitor",
    "env:ci"
  ],
  "priority": 3,
  "options": {
    "thresholds": {
      "critical": 1
    }
  }
}

Respuesta

OK

Object describing a monitor.

Expand All

Campo

Tipo

Descripción

created

date-time

Timestamp of the monitor creation.

creator

object

Object describing the creator of the shared element.

email

string

Email of the creator.

handle

string

Handle of the creator.

name

string

Name of the creator.

deleted

date-time

Whether or not the monitor is deleted. (Always null)

id

int64

ID of this monitor.

matching_downtimes

[object]

A list of active v1 downtimes that match this monitor.

end

int64

POSIX timestamp to end the downtime.

id [required]

int64

The downtime ID.

scope

[string]

The scope(s) to which the downtime applies. Must be in key:value format. For example, host:app2. Provide multiple scopes as a comma-separated list like env:dev,env:prod. The resulting downtime applies to sources that matches ALL provided scopes (env:dev AND env:prod).

start

int64

POSIX timestamp to start the downtime.

message

string

A message to include with notifications for this monitor.

modified

date-time

Last timestamp when the monitor was edited.

multi

boolean

Whether or not the monitor is broken down on different groups.

name

string

The monitor name.

options

object

List of options associated with your monitor.

aggregation

object

Type of aggregation performed in the monitor query.

group_by

string

Group to break down the monitor on.

metric

string

Metric name used in the monitor.

type

string

Metric type used in the monitor.

device_ids

[string]

DEPRECATED: IDs of the device the Synthetics monitor is running on.

enable_logs_sample

boolean

Whether or not to send a log sample when the log monitor triggers.

enable_samples

boolean

Whether or not to send a list of samples when the monitor triggers. This is only used by CI Test and Pipeline monitors.

escalation_message

string

We recommend using the is_renotify, block in the original message instead. A message to include with a re-notification. Supports the @username notification we allow elsewhere. Not applicable if renotify_interval is None.

evaluation_delay

int64

Time (in seconds) to delay evaluation, as a non-negative integer. For example, if the value is set to 300 (5min), the timeframe is set to last_5m and the time is 7:00, the monitor evaluates data from 6:50 to 6:55. This is useful for AWS CloudWatch and other backfilled metrics to ensure the monitor always has data during evaluation.

group_retention_duration

string

The time span after which groups with missing data are dropped from the monitor state. The minimum value is one hour, and the maximum value is 72 hours. Example values are: "60m", "1h", and "2d". This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors.

groupby_simple_monitor

boolean

DEPRECATED: Whether the log alert monitor triggers a single alert or multiple alerts when any group breaches a threshold. Use notify_by instead.

include_tags

boolean

A Boolean indicating whether notifications from this monitor automatically inserts its triggering tags into the title.

Examples

  • If True, [Triggered on {host:h1}] Monitor Title
  • If False, [Triggered] Monitor Title

default: true

locked

boolean

DEPRECATED: Whether or not the monitor is locked (only editable by creator and admins). Use restricted_roles instead.

min_failure_duration

int64

How long the test should be in failure before alerting (integer, number of seconds, max 7200).

min_location_failed

int64

The minimum number of locations in failure at the same time during at least one moment in the min_failure_duration period (min_location_failed and min_failure_duration are part of the advanced alerting rules - integer, >= 1).

default: 1

new_group_delay

int64

Time (in seconds) to skip evaluations for new groups.

For example, this option can be used to skip evaluations for new hosts while they initialize.

Must be a non negative integer.

new_host_delay

int64

DEPRECATED: Time (in seconds) to allow a host to boot and applications to fully start before starting the evaluation of monitor results. Should be a non negative integer.

Use new_group_delay instead.

default: 300

no_data_timeframe

int64

The number of minutes before a monitor notifies after data stops reporting. Datadog recommends at least 2x the monitor timeframe for query alerts or 2 minutes for service checks. If omitted, 2x the evaluation timeframe is used for query alerts, and 24 hours is used for service checks.

notification_preset_name

enum

Toggles the display of additional content sent in the monitor notification. Allowed enum values: show_all,hide_query,hide_handles,hide_all

default: show_all

notify_audit

boolean

A Boolean indicating whether tagged users is notified on changes to this monitor.

notify_by

[string]

Controls what granularity a monitor alerts on. Only available for monitors with groupings. For instance, a monitor grouped by cluster, namespace, and pod can be configured to only notify on each new cluster violating the alert conditions by setting notify_by to ["cluster"]. Tags mentioned in notify_by must be a subset of the grouping tags in the query. For example, a query grouped by cluster and namespace cannot notify on region. Setting notify_by to [*] configures the monitor to notify as a simple-alert.

notify_no_data

boolean

A Boolean indicating whether this monitor notifies when data stops reporting. Defaults to false.

on_missing_data

enum

Controls how groups or monitors are treated if an evaluation does not return any data points. The default option results in different behavior depending on the monitor query type. For monitors using Count queries, an empty monitor evaluation is treated as 0 and is compared to the threshold conditions. For monitors using any query type other than Count, for example Gauge, Measure, or Rate, the monitor shows the last known status. This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors. Allowed enum values: default,show_no_data,show_and_notify_no_data,resolve

renotify_interval

int64

The number of minutes after the last notification before a monitor re-notifies on the current status. It only re-notifies if it’s not resolved.

renotify_occurrences

int64

The number of times re-notification messages should be sent on the current status at the provided re-notification interval.

renotify_statuses

[string]

The types of monitor statuses for which re-notification messages are sent. Default: null if renotify_interval is null. If renotify_interval is set, defaults to renotify on Alert and No Data.

require_full_window

boolean

A Boolean indicating whether this monitor needs a full window of data before it’s evaluated. We highly recommend you set this to false for sparse metrics, otherwise some evaluations are skipped. Default is false. This setting only applies to metric monitors.

scheduling_options

object

Configuration options for scheduling.

custom_schedule

object

Configuration options for the custom schedule. This feature is in private beta.

recurrences

[object]

Array of custom schedule recurrences.

rrule

string

Defines the recurrence rule (RRULE) for a given schedule.

start

string

Defines the start date and time of the recurring schedule.

timezone

string

Defines the timezone the schedule runs on.

evaluation_window

object

Configuration options for the evaluation window. If hour_starts is set, no other fields may be set. Otherwise, day_starts and month_starts must be set together.

day_starts

string

The time of the day at which a one day cumulative evaluation window starts. Must be defined in UTC time in HH:mm format.

hour_starts

int32

The minute of the hour at which a one hour cumulative evaluation window starts.

month_starts

int32

The day of the month at which a one month cumulative evaluation window starts.

silenced

object

DEPRECATED: Information about the downtime applied to the monitor. Only shows v1 downtimes.

<any-key>

int64

UTC epoch timestamp in seconds when the downtime for the group expires.

synthetics_check_id

string

DEPRECATED: ID of the corresponding Synthetic check.

threshold_windows

object

Alerting time window options.

recovery_window

string

Describes how long an anomalous metric must be normal before the alert recovers.

trigger_window

string

Describes how long a metric must be anomalous before an alert triggers.

thresholds

object

List of the different monitor threshold available.

critical

double

The monitor CRITICAL threshold.

critical_recovery

double

The monitor CRITICAL recovery threshold.

ok

double

The monitor OK threshold.

unknown

double

The monitor UNKNOWN threshold.

warning

double

The monitor WARNING threshold.

warning_recovery

double

The monitor WARNING recovery threshold.

timeout_h

int64

The number of hours of the monitor not reporting data before it automatically resolves from a triggered state. The minimum allowed value is 0 hours. The maximum allowed value is 24 hours.

variables

[ <oneOf>]

List of requests that can be used in the monitor query. This feature is currently in beta.

Option 1

object

A formula and functions events query.

compute [required]

object

Compute options.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

interval

int64

A time interval in milliseconds.

metric

string

Measurable attribute to compute.

data_source [required]

enum

Data source for event platform-based queries. Allowed enum values: rum,ci_pipelines,ci_tests,audit,events,logs,spans,database_queries,network

group_by

[object]

Group by options.

facet [required]

string

Event facet.

limit

int64

Number of groups to return.

sort

object

Options for sorting group by results.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

metric

string

Metric used for sorting group by results.

order

enum

Direction of sort. Allowed enum values: asc,desc

default: desc

indexes

[string]

An array of index names to query in the stream. Omit or use [] to query all indexes at once.

name [required]

string

Name of the query for use in formulas.

search

object

Search options.

query [required]

string

Events search string.

overall_state

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

priority

int64

Integer from 1 (high) to 5 (low) indicating alert severity.

query [required]

string

The monitor query.

restricted_roles

[string]

A list of unique role identifiers to define which roles are allowed to edit the monitor. The unique identifiers for all roles can be pulled from the Roles API and are located in the data.id field. Editing a monitor includes any updates to the monitor configuration, monitor deletion, and muting of the monitor for any amount of time. You can use the Restriction Policies API to manage write authorization for individual monitors by teams and users, in addition to roles.

state

object

Wrapper object with the different monitor states.

groups

object

Dictionary where the keys are groups (comma separated lists of tags) and the values are the list of groups your monitor is broken down on.

<any-key>

object

Monitor state for a single group.

last_nodata_ts

int64

Latest timestamp the monitor was in NO_DATA state.

last_notified_ts

int64

Latest timestamp of the notification sent for this monitor group.

last_resolved_ts

int64

Latest timestamp the monitor group was resolved.

last_triggered_ts

int64

Latest timestamp the monitor group triggered.

name

string

The name of the monitor.

status

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

tags

[string]

Tags associated to your monitor.

type [required]

enum

The type of the monitor. For more information about type, see the monitor options docs. Allowed enum values: composite,event alert,log alert,metric alert,process alert,query alert,rum alert,service check,synthetics alert,trace-analytics alert,slo alert,event-v2 alert,audit alert,ci-pipelines alert,ci-tests alert,error-tracking alert,database-monitoring alert,network-performance alert

{
  "created": "2019-09-19T10:00:00.000Z",
  "creator": {
    "email": "string",
    "handle": "string",
    "name": "string"
  },
  "deleted": "2019-09-19T10:00:00.000Z",
  "id": "integer",
  "matching_downtimes": [
    {
      "end": 1412792983,
      "id": 1625,
      "scope": [
        "env:staging"
      ],
      "start": 1412792983
    }
  ],
  "message": "string",
  "modified": "2019-09-19T10:00:00.000Z",
  "multi": false,
  "name": "My monitor",
  "options": {
    "aggregation": {
      "group_by": "host",
      "metric": "metrics.name",
      "type": "count"
    },
    "device_ids": [],
    "enable_logs_sample": false,
    "enable_samples": false,
    "escalation_message": "string",
    "evaluation_delay": "integer",
    "group_retention_duration": "string",
    "groupby_simple_monitor": false,
    "include_tags": false,
    "locked": false,
    "min_failure_duration": "integer",
    "min_location_failed": "integer",
    "new_group_delay": "integer",
    "new_host_delay": "integer",
    "no_data_timeframe": "integer",
    "notification_preset_name": "string",
    "notify_audit": false,
    "notify_by": [],
    "notify_no_data": false,
    "on_missing_data": "string",
    "renotify_interval": "integer",
    "renotify_occurrences": "integer",
    "renotify_statuses": [],
    "require_full_window": false,
    "scheduling_options": {
      "custom_schedule": {
        "recurrences": [
          {
            "rrule": "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR",
            "start": "2023-08-31T16:30:00",
            "timezone": "Europe/Paris"
          }
        ]
      },
      "evaluation_window": {
        "day_starts": "04:00",
        "hour_starts": 0,
        "month_starts": 1
      }
    },
    "silenced": {
      "<any-key>": "integer"
    },
    "synthetics_check_id": "string",
    "threshold_windows": {
      "recovery_window": "string",
      "trigger_window": "string"
    },
    "thresholds": {
      "critical": "number",
      "critical_recovery": "number",
      "ok": "number",
      "unknown": "number",
      "warning": "number",
      "warning_recovery": "number"
    },
    "timeout_h": "integer",
    "variables": [
      {
        "compute": {
          "aggregation": "avg",
          "interval": 60000,
          "metric": "@duration"
        },
        "data_source": "rum",
        "group_by": [
          {
            "facet": "status",
            "limit": 10,
            "sort": {
              "aggregation": "avg",
              "metric": "string",
              "order": "string"
            }
          }
        ],
        "indexes": [
          "days-3",
          "days-7"
        ],
        "name": "query_errors",
        "search": {
          "query": "service:query"
        }
      }
    ]
  },
  "overall_state": "string",
  "priority": "integer",
  "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} > 100",
  "restricted_roles": [],
  "state": {
    "groups": {
      "<any-key>": {
        "last_nodata_ts": "integer",
        "last_notified_ts": "integer",
        "last_resolved_ts": "integer",
        "last_triggered_ts": "integer",
        "name": "string",
        "status": "string"
      }
    }
  },
  "tags": [],
  "type": "query alert"
}

Bad Request

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Forbidden

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Too many requests

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Ejemplo de código

                          ## json-request-body
# 

# Curl command
curl -X POST "https://api.ap1.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v1/monitor" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "message": "You may need to add web hosts if this is consistently high.", "name": "Bytes received on host0", "options": { "no_data_timeframe": 20, "notify_no_data": true }, "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} \u003e 100", "tags": [ "app:webserver", "frontend" ], "type": "query alert" } EOF
                          ## json-request-body
# 

# Curl command
curl -X POST "https://api.ap1.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v1/monitor" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "message": "You may need to add web hosts if this is consistently high.", "name": "Bytes received on host0", "options": { "no_data_timeframe": 20, "notify_no_data": true }, "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} \u003e 100", "tags": [ "app:webserver", "frontend" ], "type": "query alert" } EOF
                          ## json-request-body
# 

# Curl command
curl -X POST "https://api.ap1.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v1/monitor" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "message": "You may need to add web hosts if this is consistently high.", "name": "Bytes received on host0", "options": { "no_data_timeframe": 20, "notify_no_data": true }, "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} \u003e 100", "tags": [ "app:webserver", "frontend" ], "type": "query alert" } EOF
// Create a RUM formula and functions monitor returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV1"
)

func main() {
	body := datadogV1.Monitor{
		Name:    datadog.PtrString("Example-Monitor"),
		Type:    datadogV1.MONITORTYPE_RUM_ALERT,
		Query:   `formula("query2 / query1 * 100").last("15m") >= 0.8`,
		Message: datadog.PtrString("some message Notify: @hipchat-channel"),
		Tags: []string{
			"test:examplemonitor",
			"env:ci",
		},
		Priority: *datadog.NewNullableInt64(datadog.PtrInt64(3)),
		Options: &datadogV1.MonitorOptions{
			Thresholds: &datadogV1.MonitorThresholds{
				Critical: datadog.PtrFloat64(0.8),
			},
			Variables: []datadogV1.MonitorFormulaAndFunctionQueryDefinition{
				datadogV1.MonitorFormulaAndFunctionQueryDefinition{
					MonitorFormulaAndFunctionEventQueryDefinition: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinition{
						DataSource: datadogV1.MONITORFORMULAANDFUNCTIONEVENTSDATASOURCE_RUM,
						Name:       "query2",
						Search: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionSearch{
							Query: "",
						},
						Indexes: []string{
							"*",
						},
						Compute: datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionCompute{
							Aggregation: datadogV1.MONITORFORMULAANDFUNCTIONEVENTAGGREGATION_COUNT,
						},
						GroupBy: []datadogV1.MonitorFormulaAndFunctionEventQueryGroupBy{},
					}},
				datadogV1.MonitorFormulaAndFunctionQueryDefinition{
					MonitorFormulaAndFunctionEventQueryDefinition: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinition{
						DataSource: datadogV1.MONITORFORMULAANDFUNCTIONEVENTSDATASOURCE_RUM,
						Name:       "query1",
						Search: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionSearch{
							Query: "status:error",
						},
						Indexes: []string{
							"*",
						},
						Compute: datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionCompute{
							Aggregation: datadogV1.MONITORFORMULAANDFUNCTIONEVENTAGGREGATION_COUNT,
						},
						GroupBy: []datadogV1.MonitorFormulaAndFunctionEventQueryGroupBy{},
					}},
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV1.NewMonitorsApi(apiClient)
	resp, r, err := api.CreateMonitor(ctx, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `MonitorsApi.CreateMonitor`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `MonitorsApi.CreateMonitor`:\n%s\n", responseContent)
}
// Create a ci-pipelines formula and functions monitor returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV1"
)

func main() {
	body := datadogV1.Monitor{
		Name:    datadog.PtrString("Example-Monitor"),
		Type:    datadogV1.MONITORTYPE_CI_PIPELINES_ALERT,
		Query:   `formula("query1 / query2 * 100").last("15m") >= 0.8`,
		Message: datadog.PtrString("some message Notify: @hipchat-channel"),
		Tags: []string{
			"test:examplemonitor",
			"env:ci",
		},
		Priority: *datadog.NewNullableInt64(datadog.PtrInt64(3)),
		Options: &datadogV1.MonitorOptions{
			Thresholds: &datadogV1.MonitorThresholds{
				Critical: datadog.PtrFloat64(0.8),
			},
			Variables: []datadogV1.MonitorFormulaAndFunctionQueryDefinition{
				datadogV1.MonitorFormulaAndFunctionQueryDefinition{
					MonitorFormulaAndFunctionEventQueryDefinition: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinition{
						DataSource: datadogV1.MONITORFORMULAANDFUNCTIONEVENTSDATASOURCE_CI_PIPELINES,
						Name:       "query1",
						Search: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionSearch{
							Query: "@ci.status:error",
						},
						Indexes: []string{
							"*",
						},
						Compute: datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionCompute{
							Aggregation: datadogV1.MONITORFORMULAANDFUNCTIONEVENTAGGREGATION_COUNT,
						},
						GroupBy: []datadogV1.MonitorFormulaAndFunctionEventQueryGroupBy{},
					}},
				datadogV1.MonitorFormulaAndFunctionQueryDefinition{
					MonitorFormulaAndFunctionEventQueryDefinition: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinition{
						DataSource: datadogV1.MONITORFORMULAANDFUNCTIONEVENTSDATASOURCE_CI_PIPELINES,
						Name:       "query2",
						Search: &datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionSearch{
							Query: "",
						},
						Indexes: []string{
							"*",
						},
						Compute: datadogV1.MonitorFormulaAndFunctionEventQueryDefinitionCompute{
							Aggregation: datadogV1.MONITORFORMULAANDFUNCTIONEVENTAGGREGATION_COUNT,
						},
						GroupBy: []datadogV1.MonitorFormulaAndFunctionEventQueryGroupBy{},
					}},
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV1.NewMonitorsApi(apiClient)
	resp, r, err := api.CreateMonitor(ctx, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `MonitorsApi.CreateMonitor`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `MonitorsApi.CreateMonitor`:\n%s\n", responseContent)
}
// Create a ci-pipelines monitor returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV1"
)

func main() {
	body := datadogV1.Monitor{
		Name:    datadog.PtrString("Example-Monitor"),
		Type:    datadogV1.MONITORTYPE_CI_PIPELINES_ALERT,
		Query:   `ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1`,
		Message: datadog.PtrString("some message Notify: @hipchat-channel"),
		Tags: []string{
			"test:examplemonitor",
			"env:ci",
		},
		Priority: *datadog.NewNullableInt64(datadog.PtrInt64(3)),
		Options: &datadogV1.MonitorOptions{
			Thresholds: &datadogV1.MonitorThresholds{
				Critical: datadog.PtrFloat64(1),
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV1.NewMonitorsApi(apiClient)
	resp, r, err := api.CreateMonitor(ctx, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `MonitorsApi.CreateMonitor`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `MonitorsApi.CreateMonitor`:\n%s\n", responseContent)
}

Instructions

First install the library and its dependencies and then save the example to main.go and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
// Create a RUM formula and functions monitor returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.MonitorsApi;
import com.datadog.api.client.v1.model.Monitor;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventAggregation;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinition;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinitionCompute;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinitionSearch;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventsDataSource;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionQueryDefinition;
import com.datadog.api.client.v1.model.MonitorOptions;
import com.datadog.api.client.v1.model.MonitorThresholds;
import com.datadog.api.client.v1.model.MonitorType;
import java.util.Arrays;
import java.util.Collections;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    Monitor body =
        new Monitor()
            .name("Example-Monitor")
            .type(MonitorType.RUM_ALERT)
            .query("""
formula("query2 / query1 * 100").last("15m") >= 0.8
""")
            .message("some message Notify: @hipchat-channel")
            .tags(Arrays.asList("test:examplemonitor", "env:ci"))
            .priority(3L)
            .options(
                new MonitorOptions()
                    .thresholds(new MonitorThresholds().critical(0.8))
                    .variables(
                        Arrays.asList(
                            new MonitorFormulaAndFunctionQueryDefinition(
                                new MonitorFormulaAndFunctionEventQueryDefinition()
                                    .dataSource(MonitorFormulaAndFunctionEventsDataSource.RUM)
                                    .name("query2")
                                    .search(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionSearch()
                                            .query(""))
                                    .indexes(Collections.singletonList("*"))
                                    .compute(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionCompute()
                                            .aggregation(
                                                MonitorFormulaAndFunctionEventAggregation.COUNT))),
                            new MonitorFormulaAndFunctionQueryDefinition(
                                new MonitorFormulaAndFunctionEventQueryDefinition()
                                    .dataSource(MonitorFormulaAndFunctionEventsDataSource.RUM)
                                    .name("query1")
                                    .search(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionSearch()
                                            .query("status:error"))
                                    .indexes(Collections.singletonList("*"))
                                    .compute(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionCompute()
                                            .aggregation(
                                                MonitorFormulaAndFunctionEventAggregation
                                                    .COUNT))))));

    try {
      Monitor result = apiInstance.createMonitor(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling MonitorsApi#createMonitor");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
// Create a ci-pipelines formula and functions monitor returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.MonitorsApi;
import com.datadog.api.client.v1.model.Monitor;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventAggregation;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinition;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinitionCompute;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventQueryDefinitionSearch;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionEventsDataSource;
import com.datadog.api.client.v1.model.MonitorFormulaAndFunctionQueryDefinition;
import com.datadog.api.client.v1.model.MonitorOptions;
import com.datadog.api.client.v1.model.MonitorThresholds;
import com.datadog.api.client.v1.model.MonitorType;
import java.util.Arrays;
import java.util.Collections;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    Monitor body =
        new Monitor()
            .name("Example-Monitor")
            .type(MonitorType.CI_PIPELINES_ALERT)
            .query("""
formula("query1 / query2 * 100").last("15m") >= 0.8
""")
            .message("some message Notify: @hipchat-channel")
            .tags(Arrays.asList("test:examplemonitor", "env:ci"))
            .priority(3L)
            .options(
                new MonitorOptions()
                    .thresholds(new MonitorThresholds().critical(0.8))
                    .variables(
                        Arrays.asList(
                            new MonitorFormulaAndFunctionQueryDefinition(
                                new MonitorFormulaAndFunctionEventQueryDefinition()
                                    .dataSource(
                                        MonitorFormulaAndFunctionEventsDataSource.CI_PIPELINES)
                                    .name("query1")
                                    .search(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionSearch()
                                            .query("@ci.status:error"))
                                    .indexes(Collections.singletonList("*"))
                                    .compute(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionCompute()
                                            .aggregation(
                                                MonitorFormulaAndFunctionEventAggregation.COUNT))),
                            new MonitorFormulaAndFunctionQueryDefinition(
                                new MonitorFormulaAndFunctionEventQueryDefinition()
                                    .dataSource(
                                        MonitorFormulaAndFunctionEventsDataSource.CI_PIPELINES)
                                    .name("query2")
                                    .search(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionSearch()
                                            .query(""))
                                    .indexes(Collections.singletonList("*"))
                                    .compute(
                                        new MonitorFormulaAndFunctionEventQueryDefinitionCompute()
                                            .aggregation(
                                                MonitorFormulaAndFunctionEventAggregation
                                                    .COUNT))))));

    try {
      Monitor result = apiInstance.createMonitor(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling MonitorsApi#createMonitor");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
// Create a ci-pipelines monitor returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.MonitorsApi;
import com.datadog.api.client.v1.model.Monitor;
import com.datadog.api.client.v1.model.MonitorOptions;
import com.datadog.api.client.v1.model.MonitorThresholds;
import com.datadog.api.client.v1.model.MonitorType;
import java.util.Arrays;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    Monitor body =
        new Monitor()
            .name("Example-Monitor")
            .type(MonitorType.CI_PIPELINES_ALERT)
            .query(
                """
ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1
""")
            .message("some message Notify: @hipchat-channel")
            .tags(Arrays.asList("test:examplemonitor", "env:ci"))
            .priority(3L)
            .options(new MonitorOptions().thresholds(new MonitorThresholds().critical(1.0)));

    try {
      Monitor result = apiInstance.createMonitor(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling MonitorsApi#createMonitor");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Instructions

First install the library and its dependencies and then save the example to Example.java and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
from datadog import initialize, api

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

initialize(**options)

# Create a new monitor
monitor_options = {
    "notify_no_data": True,
    "no_data_timeframe": 20
}
tags = ["app:webserver", "frontend"]
api.Monitor.create(
    type="query alert",
    query="avg(last_5m):sum:system.net.bytes_rcvd{host:host0} > 100",
    name="Bytes received on host0",
    message="We may need to add web hosts if this is consistently high.",
    tags=tags,
    options=monitor_options
)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python "example.py"
"""
Create a RUM formula and functions monitor returns "OK" response
"""

from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v1.api.monitors_api import MonitorsApi
from datadog_api_client.v1.model.monitor import Monitor
from datadog_api_client.v1.model.monitor_formula_and_function_event_aggregation import (
    MonitorFormulaAndFunctionEventAggregation,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition import (
    MonitorFormulaAndFunctionEventQueryDefinition,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition_compute import (
    MonitorFormulaAndFunctionEventQueryDefinitionCompute,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition_search import (
    MonitorFormulaAndFunctionEventQueryDefinitionSearch,
)
from datadog_api_client.v1.model.monitor_formula_and_function_events_data_source import (
    MonitorFormulaAndFunctionEventsDataSource,
)
from datadog_api_client.v1.model.monitor_options import MonitorOptions
from datadog_api_client.v1.model.monitor_thresholds import MonitorThresholds
from datadog_api_client.v1.model.monitor_type import MonitorType

body = Monitor(
    name="Example-Monitor",
    type=MonitorType.RUM_ALERT,
    query='formula("query2 / query1 * 100").last("15m") >= 0.8',
    message="some message Notify: @hipchat-channel",
    tags=[
        "test:examplemonitor",
        "env:ci",
    ],
    priority=3,
    options=MonitorOptions(
        thresholds=MonitorThresholds(
            critical=0.8,
        ),
        variables=[
            MonitorFormulaAndFunctionEventQueryDefinition(
                data_source=MonitorFormulaAndFunctionEventsDataSource.RUM,
                name="query2",
                search=MonitorFormulaAndFunctionEventQueryDefinitionSearch(
                    query="",
                ),
                indexes=[
                    "*",
                ],
                compute=MonitorFormulaAndFunctionEventQueryDefinitionCompute(
                    aggregation=MonitorFormulaAndFunctionEventAggregation.COUNT,
                ),
                group_by=[],
            ),
            MonitorFormulaAndFunctionEventQueryDefinition(
                data_source=MonitorFormulaAndFunctionEventsDataSource.RUM,
                name="query1",
                search=MonitorFormulaAndFunctionEventQueryDefinitionSearch(
                    query="status:error",
                ),
                indexes=[
                    "*",
                ],
                compute=MonitorFormulaAndFunctionEventQueryDefinitionCompute(
                    aggregation=MonitorFormulaAndFunctionEventAggregation.COUNT,
                ),
                group_by=[],
            ),
        ],
    ),
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = MonitorsApi(api_client)
    response = api_instance.create_monitor(body=body)

    print(response)
"""
Create a ci-pipelines formula and functions monitor returns "OK" response
"""

from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v1.api.monitors_api import MonitorsApi
from datadog_api_client.v1.model.monitor import Monitor
from datadog_api_client.v1.model.monitor_formula_and_function_event_aggregation import (
    MonitorFormulaAndFunctionEventAggregation,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition import (
    MonitorFormulaAndFunctionEventQueryDefinition,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition_compute import (
    MonitorFormulaAndFunctionEventQueryDefinitionCompute,
)
from datadog_api_client.v1.model.monitor_formula_and_function_event_query_definition_search import (
    MonitorFormulaAndFunctionEventQueryDefinitionSearch,
)
from datadog_api_client.v1.model.monitor_formula_and_function_events_data_source import (
    MonitorFormulaAndFunctionEventsDataSource,
)
from datadog_api_client.v1.model.monitor_options import MonitorOptions
from datadog_api_client.v1.model.monitor_thresholds import MonitorThresholds
from datadog_api_client.v1.model.monitor_type import MonitorType

body = Monitor(
    name="Example-Monitor",
    type=MonitorType.CI_PIPELINES_ALERT,
    query='formula("query1 / query2 * 100").last("15m") >= 0.8',
    message="some message Notify: @hipchat-channel",
    tags=[
        "test:examplemonitor",
        "env:ci",
    ],
    priority=3,
    options=MonitorOptions(
        thresholds=MonitorThresholds(
            critical=0.8,
        ),
        variables=[
            MonitorFormulaAndFunctionEventQueryDefinition(
                data_source=MonitorFormulaAndFunctionEventsDataSource.CI_PIPELINES,
                name="query1",
                search=MonitorFormulaAndFunctionEventQueryDefinitionSearch(
                    query="@ci.status:error",
                ),
                indexes=[
                    "*",
                ],
                compute=MonitorFormulaAndFunctionEventQueryDefinitionCompute(
                    aggregation=MonitorFormulaAndFunctionEventAggregation.COUNT,
                ),
                group_by=[],
            ),
            MonitorFormulaAndFunctionEventQueryDefinition(
                data_source=MonitorFormulaAndFunctionEventsDataSource.CI_PIPELINES,
                name="query2",
                search=MonitorFormulaAndFunctionEventQueryDefinitionSearch(
                    query="",
                ),
                indexes=[
                    "*",
                ],
                compute=MonitorFormulaAndFunctionEventQueryDefinitionCompute(
                    aggregation=MonitorFormulaAndFunctionEventAggregation.COUNT,
                ),
                group_by=[],
            ),
        ],
    ),
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = MonitorsApi(api_client)
    response = api_instance.create_monitor(body=body)

    print(response)
"""
Create a ci-pipelines monitor returns "OK" response
"""

from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v1.api.monitors_api import MonitorsApi
from datadog_api_client.v1.model.monitor import Monitor
from datadog_api_client.v1.model.monitor_options import MonitorOptions
from datadog_api_client.v1.model.monitor_thresholds import MonitorThresholds
from datadog_api_client.v1.model.monitor_type import MonitorType

body = Monitor(
    name="Example-Monitor",
    type=MonitorType.CI_PIPELINES_ALERT,
    query='ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1',
    message="some message Notify: @hipchat-channel",
    tags=[
        "test:examplemonitor",
        "env:ci",
    ],
    priority=3,
    options=MonitorOptions(
        thresholds=MonitorThresholds(
            critical=1.0,
        ),
    ),
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = MonitorsApi(api_client)
    response = api_instance.create_monitor(body=body)

    print(response)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
require 'dogapi'

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

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

# Create a new monitor
options = {
  'notify_no_data' => true,
  'no_data_timeframe' => 20
}
tags = ['app:webserver', 'frontend']
dog.monitor(
  'query alert',
  'avg(last_5m):sum:system.net.bytes_rcvd{host:host0} > 100',
  name: 'Bytes received on host0',
  message: 'We may need to add web hosts if this is consistently high.',
  tags: tags,
  options: options
)

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
# Create a RUM formula and functions monitor returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V1::MonitorsAPI.new

body = DatadogAPIClient::V1::Monitor.new({
  name: "Example-Monitor",
  type: DatadogAPIClient::V1::MonitorType::RUM_ALERT,
  query: 'formula("query2 / query1 * 100").last("15m") >= 0.8',
  message: "some message Notify: @hipchat-channel",
  tags: [
    "test:examplemonitor",
    "env:ci",
  ],
  priority: 3,
  options: DatadogAPIClient::V1::MonitorOptions.new({
    thresholds: DatadogAPIClient::V1::MonitorThresholds.new({
      critical: 0.8,
    }),
    variables: [
      DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinition.new({
        data_source: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventsDataSource::RUM,
        name: "query2",
        search: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionSearch.new({
          query: "",
        }),
        indexes: [
          "*",
        ],
        compute: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionCompute.new({
          aggregation: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventAggregation::COUNT,
        }),
        group_by: [],
      }),
      DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinition.new({
        data_source: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventsDataSource::RUM,
        name: "query1",
        search: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionSearch.new({
          query: "status:error",
        }),
        indexes: [
          "*",
        ],
        compute: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionCompute.new({
          aggregation: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventAggregation::COUNT,
        }),
        group_by: [],
      }),
    ],
  }),
})
p api_instance.create_monitor(body)
# Create a ci-pipelines formula and functions monitor returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V1::MonitorsAPI.new

body = DatadogAPIClient::V1::Monitor.new({
  name: "Example-Monitor",
  type: DatadogAPIClient::V1::MonitorType::CI_PIPELINES_ALERT,
  query: 'formula("query1 / query2 * 100").last("15m") >= 0.8',
  message: "some message Notify: @hipchat-channel",
  tags: [
    "test:examplemonitor",
    "env:ci",
  ],
  priority: 3,
  options: DatadogAPIClient::V1::MonitorOptions.new({
    thresholds: DatadogAPIClient::V1::MonitorThresholds.new({
      critical: 0.8,
    }),
    variables: [
      DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinition.new({
        data_source: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventsDataSource::CI_PIPELINES,
        name: "query1",
        search: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionSearch.new({
          query: "@ci.status:error",
        }),
        indexes: [
          "*",
        ],
        compute: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionCompute.new({
          aggregation: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventAggregation::COUNT,
        }),
        group_by: [],
      }),
      DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinition.new({
        data_source: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventsDataSource::CI_PIPELINES,
        name: "query2",
        search: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionSearch.new({
          query: "",
        }),
        indexes: [
          "*",
        ],
        compute: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventQueryDefinitionCompute.new({
          aggregation: DatadogAPIClient::V1::MonitorFormulaAndFunctionEventAggregation::COUNT,
        }),
        group_by: [],
      }),
    ],
  }),
})
p api_instance.create_monitor(body)
# Create a ci-pipelines monitor returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V1::MonitorsAPI.new

body = DatadogAPIClient::V1::Monitor.new({
  name: "Example-Monitor",
  type: DatadogAPIClient::V1::MonitorType::CI_PIPELINES_ALERT,
  query: 'ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1',
  message: "some message Notify: @hipchat-channel",
  tags: [
    "test:examplemonitor",
    "env:ci",
  ],
  priority: 3,
  options: DatadogAPIClient::V1::MonitorOptions.new({
    thresholds: DatadogAPIClient::V1::MonitorThresholds.new({
      critical: 1,
    }),
  }),
})
p api_instance.create_monitor(body)

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
// Create a RUM formula and functions monitor returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_monitors::MonitorsAPI;
use datadog_api_client::datadogV1::model::Monitor;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventAggregation;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinition;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinitionCompute;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinitionSearch;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventsDataSource;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionQueryDefinition;
use datadog_api_client::datadogV1::model::MonitorOptions;
use datadog_api_client::datadogV1::model::MonitorThresholds;
use datadog_api_client::datadogV1::model::MonitorType;

#[tokio::main]
async fn main() {
    let body =
        Monitor::new(r#"formula("query2 / query1 * 100").last("15m") >= 0.8"#.to_string(), MonitorType::RUM_ALERT)
            .message("some message Notify: @hipchat-channel".to_string())
            .name("Example-Monitor".to_string())
            .options(
                MonitorOptions::new()
                    .thresholds(MonitorThresholds::new().critical(0.8 as f64))
                    .variables(
                        vec![
                            MonitorFormulaAndFunctionQueryDefinition::MonitorFormulaAndFunctionEventQueryDefinition(
                                Box::new(
                                    MonitorFormulaAndFunctionEventQueryDefinition::new(
                                        MonitorFormulaAndFunctionEventQueryDefinitionCompute::new(
                                            MonitorFormulaAndFunctionEventAggregation::COUNT,
                                        ),
                                        MonitorFormulaAndFunctionEventsDataSource::RUM,
                                        "query2".to_string(),
                                    )
                                        .group_by(vec![])
                                        .indexes(vec!["*".to_string()])
                                        .search(
                                            MonitorFormulaAndFunctionEventQueryDefinitionSearch::new("".to_string()),
                                        ),
                                ),
                            ),
                            MonitorFormulaAndFunctionQueryDefinition::MonitorFormulaAndFunctionEventQueryDefinition(
                                Box::new(
                                    MonitorFormulaAndFunctionEventQueryDefinition::new(
                                        MonitorFormulaAndFunctionEventQueryDefinitionCompute::new(
                                            MonitorFormulaAndFunctionEventAggregation::COUNT,
                                        ),
                                        MonitorFormulaAndFunctionEventsDataSource::RUM,
                                        "query1".to_string(),
                                    )
                                        .group_by(vec![])
                                        .indexes(vec!["*".to_string()])
                                        .search(
                                            MonitorFormulaAndFunctionEventQueryDefinitionSearch::new(
                                                "status:error".to_string(),
                                            ),
                                        ),
                                ),
                            )
                        ],
                    ),
            )
            .priority(Some(3))
            .tags(vec!["test:examplemonitor".to_string(), "env:ci".to_string()]);
    let configuration = datadog::Configuration::new();
    let api = MonitorsAPI::with_config(configuration);
    let resp = api.create_monitor(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
// Create a ci-pipelines formula and functions monitor returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_monitors::MonitorsAPI;
use datadog_api_client::datadogV1::model::Monitor;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventAggregation;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinition;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinitionCompute;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventQueryDefinitionSearch;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionEventsDataSource;
use datadog_api_client::datadogV1::model::MonitorFormulaAndFunctionQueryDefinition;
use datadog_api_client::datadogV1::model::MonitorOptions;
use datadog_api_client::datadogV1::model::MonitorThresholds;
use datadog_api_client::datadogV1::model::MonitorType;

#[tokio::main]
async fn main() {
    let body =
        Monitor::new(
            r#"formula("query1 / query2 * 100").last("15m") >= 0.8"#.to_string(),
            MonitorType::CI_PIPELINES_ALERT,
        )
            .message("some message Notify: @hipchat-channel".to_string())
            .name("Example-Monitor".to_string())
            .options(
                MonitorOptions::new()
                    .thresholds(MonitorThresholds::new().critical(0.8 as f64))
                    .variables(
                        vec![
                            MonitorFormulaAndFunctionQueryDefinition::MonitorFormulaAndFunctionEventQueryDefinition(
                                Box::new(
                                    MonitorFormulaAndFunctionEventQueryDefinition::new(
                                        MonitorFormulaAndFunctionEventQueryDefinitionCompute::new(
                                            MonitorFormulaAndFunctionEventAggregation::COUNT,
                                        ),
                                        MonitorFormulaAndFunctionEventsDataSource::CI_PIPELINES,
                                        "query1".to_string(),
                                    )
                                        .group_by(vec![])
                                        .indexes(vec!["*".to_string()])
                                        .search(
                                            MonitorFormulaAndFunctionEventQueryDefinitionSearch::new(
                                                "@ci.status:error".to_string(),
                                            ),
                                        ),
                                ),
                            ),
                            MonitorFormulaAndFunctionQueryDefinition::MonitorFormulaAndFunctionEventQueryDefinition(
                                Box::new(
                                    MonitorFormulaAndFunctionEventQueryDefinition::new(
                                        MonitorFormulaAndFunctionEventQueryDefinitionCompute::new(
                                            MonitorFormulaAndFunctionEventAggregation::COUNT,
                                        ),
                                        MonitorFormulaAndFunctionEventsDataSource::CI_PIPELINES,
                                        "query2".to_string(),
                                    )
                                        .group_by(vec![])
                                        .indexes(vec!["*".to_string()])
                                        .search(
                                            MonitorFormulaAndFunctionEventQueryDefinitionSearch::new("".to_string()),
                                        ),
                                ),
                            )
                        ],
                    ),
            )
            .priority(Some(3))
            .tags(vec!["test:examplemonitor".to_string(), "env:ci".to_string()]);
    let configuration = datadog::Configuration::new();
    let api = MonitorsAPI::with_config(configuration);
    let resp = api.create_monitor(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
// Create a ci-pipelines monitor returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_monitors::MonitorsAPI;
use datadog_api_client::datadogV1::model::Monitor;
use datadog_api_client::datadogV1::model::MonitorOptions;
use datadog_api_client::datadogV1::model::MonitorThresholds;
use datadog_api_client::datadogV1::model::MonitorType;

#[tokio::main]
async fn main() {
    let body =
        Monitor::new(
            r#"ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1"#.to_string(),
            MonitorType::CI_PIPELINES_ALERT,
        )
            .message("some message Notify: @hipchat-channel".to_string())
            .name("Example-Monitor".to_string())
            .options(MonitorOptions::new().thresholds(MonitorThresholds::new().critical(1.0 as f64)))
            .priority(Some(3))
            .tags(vec!["test:examplemonitor".to_string(), "env:ci".to_string()]);
    let configuration = datadog::Configuration::new();
    let api = MonitorsAPI::with_config(configuration);
    let resp = api.create_monitor(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}

Instructions

First install the library and its dependencies and then save the example to src/main.rs and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
/**
 * Create a RUM formula and functions monitor returns "OK" response
 */

import { client, v1 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v1.MonitorsApi(configuration);

const params: v1.MonitorsApiCreateMonitorRequest = {
  body: {
    name: "Example-Monitor",
    type: "rum alert",
    query: `formula("query2 / query1 * 100").last("15m") >= 0.8`,
    message: "some message Notify: @hipchat-channel",
    tags: ["test:examplemonitor", "env:ci"],
    priority: 3,
    options: {
      thresholds: {
        critical: 0.8,
      },
      variables: [
        {
          dataSource: "rum",
          name: "query2",
          search: {
            query: "",
          },
          indexes: ["*"],
          compute: {
            aggregation: "count",
          },
          groupBy: [],
        },
        {
          dataSource: "rum",
          name: "query1",
          search: {
            query: "status:error",
          },
          indexes: ["*"],
          compute: {
            aggregation: "count",
          },
          groupBy: [],
        },
      ],
    },
  },
};

apiInstance
  .createMonitor(params)
  .then((data: v1.Monitor) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
/**
 * Create a ci-pipelines formula and functions monitor returns "OK" response
 */

import { client, v1 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v1.MonitorsApi(configuration);

const params: v1.MonitorsApiCreateMonitorRequest = {
  body: {
    name: "Example-Monitor",
    type: "ci-pipelines alert",
    query: `formula("query1 / query2 * 100").last("15m") >= 0.8`,
    message: "some message Notify: @hipchat-channel",
    tags: ["test:examplemonitor", "env:ci"],
    priority: 3,
    options: {
      thresholds: {
        critical: 0.8,
      },
      variables: [
        {
          dataSource: "ci_pipelines",
          name: "query1",
          search: {
            query: "@ci.status:error",
          },
          indexes: ["*"],
          compute: {
            aggregation: "count",
          },
          groupBy: [],
        },
        {
          dataSource: "ci_pipelines",
          name: "query2",
          search: {
            query: "",
          },
          indexes: ["*"],
          compute: {
            aggregation: "count",
          },
          groupBy: [],
        },
      ],
    },
  },
};

apiInstance
  .createMonitor(params)
  .then((data: v1.Monitor) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
/**
 * Create a ci-pipelines monitor returns "OK" response
 */

import { client, v1 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v1.MonitorsApi(configuration);

const params: v1.MonitorsApiCreateMonitorRequest = {
  body: {
    name: "Example-Monitor",
    type: "ci-pipelines alert",
    query: `ci-pipelines("ci_level:pipeline @git.branch:staging* @ci.status:error").rollup("count").by("@git.branch,@ci.pipeline.name").last("5m") >= 1`,
    message: "some message Notify: @hipchat-channel",
    tags: ["test:examplemonitor", "env:ci"],
    priority: 3,
    options: {
      thresholds: {
        critical: 1,
      },
    },
  },
};

apiInstance
  .createMonitor(params)
  .then((data: v1.Monitor) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

Instructions

First install the library and its dependencies and then save the example to example.ts and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"

GET https://api.ap1.datadoghq.com/api/v1/monitor/searchhttps://api.datadoghq.eu/api/v1/monitor/searchhttps://api.ddog-gov.com/api/v1/monitor/searchhttps://api.datadoghq.com/api/v1/monitor/searchhttps://api.us3.datadoghq.com/api/v1/monitor/searchhttps://api.us5.datadoghq.com/api/v1/monitor/search

Información general

Busca y filtra los detalles de tu monitor. This endpoint requires the monitors_read permission.

OAuth apps require the monitors_read authorization scope to access this endpoint.

Argumentos

Cadenas de consulta

Nombre

Tipo

Descripción

query

string

After entering a search query in your Manage Monitor page use the query parameter value in the URL of the page as value for this parameter. Consult the dedicated manage monitor documentation page to learn more.

The query can contain any number of space-separated monitor attributes, for instance query="type:metric status:alert".

page

integer

Page to start paginating from.

per_page

integer

Number of monitors to return per page.

sort

string

String for sort order, composed of field and sort order separate by a comma, for example name,asc. Supported sort directions: asc, desc. Supported fields:

  • name
  • status
  • tags

Respuesta

OK

The response form a monitor search.

Expand All

Campo

Tipo

Descripción

counts

object

The counts of monitors per different criteria.

muted

[object]

Search facets.

count

int64

The number of found monitors with the listed value.

name

The facet value.

status

[object]

Search facets.

count

int64

The number of found monitors with the listed value.

name

The facet value.

tag

[object]

Search facets.

count

int64

The number of found monitors with the listed value.

name

The facet value.

type

[object]

Search facets.

count

int64

The number of found monitors with the listed value.

name

The facet value.

metadata

object

Metadata about the response.

page

int64

The page to start paginating from.

page_count

int64

The number of pages.

per_page

int64

The number of monitors to return per page.

total_count

int64

The total number of monitors.

monitors

[object]

The list of found monitors.

classification

string

Classification of the monitor.

creator

object

Object describing the creator of the shared element.

email

string

Email of the creator.

handle

string

Handle of the creator.

name

string

Name of the creator.

id

int64

ID of the monitor.

last_triggered_ts

int64

Latest timestamp the monitor triggered.

metrics

[string]

Metrics used by the monitor.

name

string

The monitor name.

notifications

[object]

The notification triggered by the monitor.

handle

string

The email address that received the notification.

name

string

The username receiving the notification

org_id

int64

The ID of the organization.

query

string

The monitor query.

scopes

[string]

The scope(s) to which the downtime applies, for example host:app2. Provide multiple scopes as a comma-separated list, for example env:dev,env:prod. The resulting downtime applies to sources that matches ALL provided scopes (that is env:dev AND env:prod), NOT any of them.

status

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

tags

[string]

Tags associated with the monitor.

type

enum

The type of the monitor. For more information about type, see the monitor options docs. Allowed enum values: composite,event alert,log alert,metric alert,process alert,query alert,rum alert,service check,synthetics alert,trace-analytics alert,slo alert,event-v2 alert,audit alert,ci-pipelines alert,ci-tests alert,error-tracking alert,database-monitoring alert,network-performance alert

{
  "counts": {
    "muted": [
      {
        "count": "integer",
        "name": "undefined"
      }
    ],
    "status": [
      {
        "count": "integer",
        "name": "undefined"
      }
    ],
    "tag": [
      {
        "count": "integer",
        "name": "undefined"
      }
    ],
    "type": [
      {
        "count": "integer",
        "name": "undefined"
      }
    ]
  },
  "metadata": {
    "page": "integer",
    "page_count": "integer",
    "per_page": "integer",
    "total_count": "integer"
  },
  "monitors": [
    {
      "classification": "string",
      "creator": {
        "email": "string",
        "handle": "string",
        "name": "string"
      },
      "id": "integer",
      "last_triggered_ts": "integer",
      "metrics": [],
      "name": "string",
      "notifications": [
        {
          "handle": "string",
          "name": "string"
        }
      ],
      "org_id": "integer",
      "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} > 100",
      "scopes": [
        "host:app2",
        "env:dev,env:prod"
      ],
      "status": "string",
      "tags": [],
      "type": "query alert"
    }
  ]
}

Bad Request

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Forbidden

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Too many requests

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Ejemplo de código

                  # Curl command
curl -X GET "https://api.ap1.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v1/monitor/search" \ -H "Accept: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}"
"""
Monitors search returns "OK" response
"""

from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v1.api.monitors_api import MonitorsApi

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = MonitorsApi(api_client)
    response = api_instance.search_monitors()

    print(response)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
# Monitors search returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V1::MonitorsAPI.new
p api_instance.search_monitors()

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
require 'dogapi'

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

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

# Search monitors
dog.search_monitors

# Examples of possible query parameters:
# dog.search_monitors(query="id:7100311")
# dog.search_monitors(query="title:foo metric:system.core.idle status:Alert")

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
// Monitors search returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV1"
)

func main() {
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV1.NewMonitorsApi(apiClient)
	resp, r, err := api.SearchMonitors(ctx, *datadogV1.NewSearchMonitorsOptionalParameters())

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `MonitorsApi.SearchMonitors`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `MonitorsApi.SearchMonitors`:\n%s\n", responseContent)
}

Instructions

First install the library and its dependencies and then save the example to main.go and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
// Monitors search returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.MonitorsApi;
import com.datadog.api.client.v1.model.MonitorSearchResponse;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    MonitorsApi apiInstance = new MonitorsApi(defaultClient);

    try {
      MonitorSearchResponse result = apiInstance.searchMonitors();
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling MonitorsApi#searchMonitors");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Instructions

First install the library and its dependencies and then save the example to Example.java and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
from datadog import initialize, api

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

initialize(**options)

# Search monitors
api.Monitor.search()

# Examples of possible query parameters:
# api.Monitor.search(query="id:7100311")
# api.Monitor.search(query="title:foo metric:system.core.idle status:Alert")

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python "example.py"
// Monitors search returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_monitors::MonitorsAPI;
use datadog_api_client::datadogV1::api_monitors::SearchMonitorsOptionalParams;

#[tokio::main]
async fn main() {
    let configuration = datadog::Configuration::new();
    let api = MonitorsAPI::with_config(configuration);
    let resp = api
        .search_monitors(SearchMonitorsOptionalParams::default())
        .await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}

Instructions

First install the library and its dependencies and then save the example to src/main.rs and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
/**
 * Monitors search returns "OK" response
 */

import { client, v1 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v1.MonitorsApi(configuration);

apiInstance
  .searchMonitors()
  .then((data: v1.MonitorSearchResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

Instructions

First install the library and its dependencies and then save the example to example.ts and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"

POST https://api.ap1.datadoghq.com/api/v1/monitor/{monitor_id}/unmutehttps://api.datadoghq.eu/api/v1/monitor/{monitor_id}/unmutehttps://api.ddog-gov.com/api/v1/monitor/{monitor_id}/unmutehttps://api.datadoghq.com/api/v1/monitor/{monitor_id}/unmutehttps://api.us3.datadoghq.com/api/v1/monitor/{monitor_id}/unmutehttps://api.us5.datadoghq.com/api/v1/monitor/{monitor_id}/unmute

Información general

Desactiva el silenciamiento del monitor especificado. This endpoint requires the monitors_write permission.

OAuth apps require the monitors_write authorization scope to access this endpoint.

Argumentos

Parámetros de ruta

Nombre

Tipo

Descripción

monitor_id [required]

integer

The id of the monitor

Cadenas de consulta

Nombre

Tipo

Descripción

scope

string

The scope to apply the mute to. For example, if your alert is grouped by {host}, you might mute host:app1.

all_scopes

boolean

Clear muting across all scopes. Default is false.

Respuesta

OK

Object describing a monitor.

Expand All

Campo

Tipo

Descripción

created

date-time

Timestamp of the monitor creation.

creator

object

Object describing the creator of the shared element.

email

string

Email of the creator.

handle

string

Handle of the creator.

name

string

Name of the creator.

deleted

date-time

Whether or not the monitor is deleted. (Always null)

id

int64

ID of this monitor.

matching_downtimes

[object]

A list of active v1 downtimes that match this monitor.

end

int64

POSIX timestamp to end the downtime.

id [required]

int64

The downtime ID.

scope

[string]

The scope(s) to which the downtime applies. Must be in key:value format. For example, host:app2. Provide multiple scopes as a comma-separated list like env:dev,env:prod. The resulting downtime applies to sources that matches ALL provided scopes (env:dev AND env:prod).

start

int64

POSIX timestamp to start the downtime.

message

string

A message to include with notifications for this monitor.

modified

date-time

Last timestamp when the monitor was edited.

multi

boolean

Whether or not the monitor is broken down on different groups.

name

string

The monitor name.

options

object

List of options associated with your monitor.

aggregation

object

Type of aggregation performed in the monitor query.

group_by

string

Group to break down the monitor on.

metric

string

Metric name used in the monitor.

type

string

Metric type used in the monitor.

device_ids

[string]

DEPRECATED: IDs of the device the Synthetics monitor is running on.

enable_logs_sample

boolean

Whether or not to send a log sample when the log monitor triggers.

enable_samples

boolean

Whether or not to send a list of samples when the monitor triggers. This is only used by CI Test and Pipeline monitors.

escalation_message

string

We recommend using the is_renotify, block in the original message instead. A message to include with a re-notification. Supports the @username notification we allow elsewhere. Not applicable if renotify_interval is None.

evaluation_delay

int64

Time (in seconds) to delay evaluation, as a non-negative integer. For example, if the value is set to 300 (5min), the timeframe is set to last_5m and the time is 7:00, the monitor evaluates data from 6:50 to 6:55. This is useful for AWS CloudWatch and other backfilled metrics to ensure the monitor always has data during evaluation.

group_retention_duration

string

The time span after which groups with missing data are dropped from the monitor state. The minimum value is one hour, and the maximum value is 72 hours. Example values are: "60m", "1h", and "2d". This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors.

groupby_simple_monitor

boolean

DEPRECATED: Whether the log alert monitor triggers a single alert or multiple alerts when any group breaches a threshold. Use notify_by instead.

include_tags

boolean

A Boolean indicating whether notifications from this monitor automatically inserts its triggering tags into the title.

Examples

  • If True, [Triggered on {host:h1}] Monitor Title
  • If False, [Triggered] Monitor Title

default: true

locked

boolean

DEPRECATED: Whether or not the monitor is locked (only editable by creator and admins). Use restricted_roles instead.

min_failure_duration

int64

How long the test should be in failure before alerting (integer, number of seconds, max 7200).

min_location_failed

int64

The minimum number of locations in failure at the same time during at least one moment in the min_failure_duration period (min_location_failed and min_failure_duration are part of the advanced alerting rules - integer, >= 1).

default: 1

new_group_delay

int64

Time (in seconds) to skip evaluations for new groups.

For example, this option can be used to skip evaluations for new hosts while they initialize.

Must be a non negative integer.

new_host_delay

int64

DEPRECATED: Time (in seconds) to allow a host to boot and applications to fully start before starting the evaluation of monitor results. Should be a non negative integer.

Use new_group_delay instead.

default: 300

no_data_timeframe

int64

The number of minutes before a monitor notifies after data stops reporting. Datadog recommends at least 2x the monitor timeframe for query alerts or 2 minutes for service checks. If omitted, 2x the evaluation timeframe is used for query alerts, and 24 hours is used for service checks.

notification_preset_name

enum

Toggles the display of additional content sent in the monitor notification. Allowed enum values: show_all,hide_query,hide_handles,hide_all

default: show_all

notify_audit

boolean

A Boolean indicating whether tagged users is notified on changes to this monitor.

notify_by

[string]

Controls what granularity a monitor alerts on. Only available for monitors with groupings. For instance, a monitor grouped by cluster, namespace, and pod can be configured to only notify on each new cluster violating the alert conditions by setting notify_by to ["cluster"]. Tags mentioned in notify_by must be a subset of the grouping tags in the query. For example, a query grouped by cluster and namespace cannot notify on region. Setting notify_by to [*] configures the monitor to notify as a simple-alert.

notify_no_data

boolean

A Boolean indicating whether this monitor notifies when data stops reporting. Defaults to false.

on_missing_data

enum

Controls how groups or monitors are treated if an evaluation does not return any data points. The default option results in different behavior depending on the monitor query type. For monitors using Count queries, an empty monitor evaluation is treated as 0 and is compared to the threshold conditions. For monitors using any query type other than Count, for example Gauge, Measure, or Rate, the monitor shows the last known status. This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors. Allowed enum values: default,show_no_data,show_and_notify_no_data,resolve

renotify_interval

int64

The number of minutes after the last notification before a monitor re-notifies on the current status. It only re-notifies if it’s not resolved.

renotify_occurrences

int64

The number of times re-notification messages should be sent on the current status at the provided re-notification interval.

renotify_statuses

[string]

The types of monitor statuses for which re-notification messages are sent. Default: null if renotify_interval is null. If renotify_interval is set, defaults to renotify on Alert and No Data.

require_full_window

boolean

A Boolean indicating whether this monitor needs a full window of data before it’s evaluated. We highly recommend you set this to false for sparse metrics, otherwise some evaluations are skipped. Default is false. This setting only applies to metric monitors.

scheduling_options

object

Configuration options for scheduling.

custom_schedule

object

Configuration options for the custom schedule. This feature is in private beta.

recurrences

[object]

Array of custom schedule recurrences.

rrule

string

Defines the recurrence rule (RRULE) for a given schedule.

start

string

Defines the start date and time of the recurring schedule.

timezone

string

Defines the timezone the schedule runs on.

evaluation_window

object

Configuration options for the evaluation window. If hour_starts is set, no other fields may be set. Otherwise, day_starts and month_starts must be set together.

day_starts

string

The time of the day at which a one day cumulative evaluation window starts. Must be defined in UTC time in HH:mm format.

hour_starts

int32

The minute of the hour at which a one hour cumulative evaluation window starts.

month_starts

int32

The day of the month at which a one month cumulative evaluation window starts.

silenced

object

DEPRECATED: Information about the downtime applied to the monitor. Only shows v1 downtimes.

<any-key>

int64

UTC epoch timestamp in seconds when the downtime for the group expires.

synthetics_check_id

string

DEPRECATED: ID of the corresponding Synthetic check.

threshold_windows

object

Alerting time window options.

recovery_window

string

Describes how long an anomalous metric must be normal before the alert recovers.

trigger_window

string

Describes how long a metric must be anomalous before an alert triggers.

thresholds

object

List of the different monitor threshold available.

critical

double

The monitor CRITICAL threshold.

critical_recovery

double

The monitor CRITICAL recovery threshold.

ok

double

The monitor OK threshold.

unknown

double

The monitor UNKNOWN threshold.

warning

double

The monitor WARNING threshold.

warning_recovery

double

The monitor WARNING recovery threshold.

timeout_h

int64

The number of hours of the monitor not reporting data before it automatically resolves from a triggered state. The minimum allowed value is 0 hours. The maximum allowed value is 24 hours.

variables

[ <oneOf>]

List of requests that can be used in the monitor query. This feature is currently in beta.

Option 1

object

A formula and functions events query.

compute [required]

object

Compute options.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

interval

int64

A time interval in milliseconds.

metric

string

Measurable attribute to compute.

data_source [required]

enum

Data source for event platform-based queries. Allowed enum values: rum,ci_pipelines,ci_tests,audit,events,logs,spans,database_queries,network

group_by

[object]

Group by options.

facet [required]

string

Event facet.

limit

int64

Number of groups to return.

sort

object

Options for sorting group by results.

aggregation [required]

enum

Aggregation methods for event platform queries. Allowed enum values: count,cardinality,median,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

metric

string

Metric used for sorting group by results.

order

enum

Direction of sort. Allowed enum values: asc,desc

default: desc

indexes

[string]

An array of index names to query in the stream. Omit or use [] to query all indexes at once.

name [required]

string

Name of the query for use in formulas.

search

object

Search options.

query [required]

string

Events search string.

overall_state

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

priority

int64

Integer from 1 (high) to 5 (low) indicating alert severity.

query [required]

string

The monitor query.

restricted_roles

[string]

A list of unique role identifiers to define which roles are allowed to edit the monitor. The unique identifiers for all roles can be pulled from the Roles API and are located in the data.id field. Editing a monitor includes any updates to the monitor configuration, monitor deletion, and muting of the monitor for any amount of time. You can use the Restriction Policies API to manage write authorization for individual monitors by teams and users, in addition to roles.

state

object

Wrapper object with the different monitor states.

groups

object

Dictionary where the keys are groups (comma separated lists of tags) and the values are the list of groups your monitor is broken down on.

<any-key>

object

Monitor state for a single group.

last_nodata_ts

int64

Latest timestamp the monitor was in NO_DATA state.

last_notified_ts

int64

Latest timestamp of the notification sent for this monitor group.

last_resolved_ts

int64

Latest timestamp the monitor group was resolved.

last_triggered_ts

int64

Latest timestamp the monitor group triggered.

name

string

The name of the monitor.

status

enum

The different states your monitor can be in. Allowed enum values: Alert,Ignored,No Data,OK,Skipped,Unknown,Warn

tags

[string]

Tags associated to your monitor.

type [required]

enum

The type of the monitor. For more information about type, see the monitor options docs. Allowed enum values: composite,event alert,log alert,metric alert,process alert,query alert,rum alert,service check,synthetics alert,trace-analytics alert,slo alert,event-v2 alert,audit alert,ci-pipelines alert,ci-tests alert,error-tracking alert,database-monitoring alert,network-performance alert

{
  "created": "2019-09-19T10:00:00.000Z",
  "creator": {
    "email": "string",
    "handle": "string",
    "name": "string"
  },
  "deleted": "2019-09-19T10:00:00.000Z",
  "id": "integer",
  "matching_downtimes": [
    {
      "end": 1412792983,
      "id": 1625,
      "scope": [
        "env:staging"
      ],
      "start": 1412792983
    }
  ],
  "message": "string",
  "modified": "2019-09-19T10:00:00.000Z",
  "multi": false,
  "name": "My monitor",
  "options": {
    "aggregation": {
      "group_by": "host",
      "metric": "metrics.name",
      "type": "count"
    },
    "device_ids": [],
    "enable_logs_sample": false,
    "enable_samples": false,
    "escalation_message": "string",
    "evaluation_delay": "integer",
    "group_retention_duration": "string",
    "groupby_simple_monitor": false,
    "include_tags": false,
    "locked": false,
    "min_failure_duration": "integer",
    "min_location_failed": "integer",
    "new_group_delay": "integer",
    "new_host_delay": "integer",
    "no_data_timeframe": "integer",
    "notification_preset_name": "string",
    "notify_audit": false,
    "notify_by": [],
    "notify_no_data": false,
    "on_missing_data": "string",
    "renotify_interval": "integer",
    "renotify_occurrences": "integer",
    "renotify_statuses": [],
    "require_full_window": false,
    "scheduling_options": {
      "custom_schedule": {
        "recurrences": [
          {
            "rrule": "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR",
            "start": "2023-08-31T16:30:00",
            "timezone": "Europe/Paris"
          }
        ]
      },
      "evaluation_window": {
        "day_starts": "04:00",
        "hour_starts": 0,
        "month_starts": 1
      }
    },
    "silenced": {
      "<any-key>": "integer"
    },
    "synthetics_check_id": "string",
    "threshold_windows": {
      "recovery_window": "string",
      "trigger_window": "string"
    },
    "thresholds": {
      "critical": "number",
      "critical_recovery": "number",
      "ok": "number",
      "unknown": "number",
      "warning": "number",
      "warning_recovery": "number"
    },
    "timeout_h": "integer",
    "variables": [
      {
        "compute": {
          "aggregation": "avg",
          "interval": 60000,
          "metric": "@duration"
        },
        "data_source": "rum",
        "group_by": [
          {
            "facet": "status",
            "limit": 10,
            "sort": {
              "aggregation": "avg",
              "metric": "string",
              "order": "string"
            }
          }
        ],
        "indexes": [
          "days-3",
          "days-7"
        ],
        "name": "query_errors",
        "search": {
          "query": "service:query"
        }
      }
    ]
  },
  "overall_state": "string",
  "priority": "integer",
  "query": "avg(last_5m):sum:system.net.bytes_rcvd{host:host0} > 100",
  "restricted_roles": [],
  "state": {
    "groups": {
      "<any-key>": {
        "last_nodata_ts": "integer",
        "last_notified_ts": "integer",
        "last_resolved_ts": "integer",
        "last_triggered_ts": "integer",
        "name": "string",
        "status": "string"
      }
    }
  },
  "tags": [],
  "type": "query alert"
}

Bad Request

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Authentication error

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Monitor Not Found error

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Too many requests

Error response object.

Expand All

Campo

Tipo

Descripción

errors [required]

[string]

Array of errors returned by the API.

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

Ejemplo de código

                  # Path parameters
export monitor_id="CHANGE_ME"
# Curl command
curl -X POST "https://api.ap1.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v1/monitor/${monitor_id}/unmute" \ -H "Accept: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}"
require 'dogapi'

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

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

# Unmute an alert
dog.unmute_monitor(62_628)

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
from datadog import initialize, api

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

initialize(**options)

# Unmute all alerts
api.Monitor.unmute(2088)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python "example.py"

GET https://api.ap1.datadoghq.com/api/v1/monitorhttps://api.datadoghq.eu/api/v1/monitorhttps://api.ddog-gov.com/api/v1/monitorhttps://api.datadoghq.com/api/v1/monitorhttps://api.us3.datadoghq.com/api/v1/monitorhttps://api.us5.datadoghq.com/api/v1/monitor

Información general

Obtén información detallada sobre el monitor especificado de tu organización. This endpoint requires the monitors_read permission.

OAuth apps require the monitors_read authorization scope to access this endpoint.

Argumentos

Cadenas de consulta

Nombre

Tipo

Descripción

group_states

string

When specified, shows additional information about the group states. Choose one or more from all, alert, warn, and no data.

name

string

A string to filter monitors by name.

tags

string

A comma separated list indicating what tags, if any, should be used to filter the list of monitors by scope. For example, host:host0.

monitor_tags

string

A comma separated list indicating what service and/or custom tags, if any, should be used to filter the list of monitors. Tags created in the Datadog UI automatically have the service key prepended. For example, service:my-app.

with_downtimes

boolean

If this argument is set to true, then the returned data includes all current active downtimes for each monitor.

id_offset

integer

Use this parameter for paginating through large sets of monitors. Start with a value of zero, make a request, set the value to the last ID of result set, and then repeat until the response is empty.

page

integer

The page to start paginating from. If this argument is not specified, the request returns all monitors without pagination.

page_size

integer

The number of monitors to return per page. If the page argument is not specified, the default behavior returns all monitors without a page_size limit. However, if page is specified and page_size is not, the argument defaults to 100.

Respuesta

OK

Expand All

Campo

Tipo

Descripción

created

date-time

Timestamp of the monitor creation.

creator

object

Object describing the creator of the shared element.

email

string

Email of the creator.

handle

string

Handle of the creator.

name

string

Name of the creator.

deleted

date-time

Whether or not the monitor is deleted. (Always null)

id

int64

ID of this monitor.

matching_downtimes

[object]

A list of active v1 downtimes that match this monitor.

end

int64

POSIX timestamp to end the downtime.

id [required]

int64

The downtime ID.

scope

[string]

The scope(s) to which the downtime applies. Must be in key:value format. For example, host:app2. Provide multiple scopes as a comma-separated list like env:dev,env:prod. The resulting downtime applies to sources that matches ALL provided scopes (env:dev AND env:prod).

start

int64

POSIX timestamp to start the downtime.

message

string

A message to include with notifications for this monitor.

modified

date-time

Last timestamp when the monitor was edited.

multi

boolean

Whether or not the monitor is broken down on different groups.

name

string

The monitor name.

options

object

List of options associated with your monitor.

aggregation

object

Type of aggregation performed in the monitor query.

group_by

string

Group to break down the monitor on.

metric

string

Metric name used in the monitor.

type

string

Metric type used in the monitor.

device_ids

[string]

DEPRECATED: IDs of the device the Synthetics monitor is running on.

enable_logs_sample

boolean

Whether or not to send a log sample when the log monitor triggers.

enable_samples

boolean

Whether or not to send a list of samples when the monitor triggers. This is only used by CI Test and Pipeline monitors.

escalation_message

string

We recommend using the is_renotify, block in the original message instead. A message to include with a re-notification. Supports the @username notification we allow elsewhere. Not applicable if renotify_interval is None.

evaluation_delay

int64

Time (in seconds) to delay evaluation, as a non-negative integer. For example, if the value is set to 300 (5min), the timeframe is set to last_5m and the time is 7:00, the monitor evaluates data from 6:50 to 6:55. This is useful for AWS CloudWatch and other backfilled metrics to ensure the monitor always has data during evaluation.

group_retention_duration

string

The time span after which groups with missing data are dropped from the monitor state. The minimum value is one hour, and the maximum value is 72 hours. Example values are: "60m", "1h", and "2d". This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors.

groupby_simple_monitor

boolean

DEPRECATED: Whether the log alert monitor triggers a single alert or multiple alerts when any group breaches a threshold. Use notify_by instead.

include_tags

boolean

A Boolean indicating whether notifications from this monitor automatically inserts its triggering tags into the title.

Examples

  • If True, [Triggered on {host:h1}] Monitor Title
  • If False, [Triggered] Monitor Title

default: true

locked

boolean

DEPRECATED: Whether or not the monitor is locked (only editable by creator and admins). Use restricted_roles instead.

min_failure_duration

int64

How long the test should be in failure before alerting (integer, number of seconds, max 7200).

min_location_failed

int64

The minimum number of locations in failure at the same time during at least one moment in the min_failure_duration period (min_location_failed and min_failure_duration are part of the advanced alerting rules - integer, >= 1).

default: 1

new_group_delay

int64

Time (in seconds) to skip evaluations for new groups.

For example, this option can be used to skip evaluations for new hosts while they initialize.

Must be a non negative integer.

new_host_delay

int64

DEPRECATED: Time (in seconds) to allow a host to boot and applications to fully start before starting the evaluation of monitor results. Should be a non negative integer.

Use new_group_delay instead.

default: 300

no_data_timeframe

int64

The number of minutes before a monitor notifies after data stops reporting. Datadog recommends at least 2x the monitor timeframe for query alerts or 2 minutes for service checks. If omitted, 2x the evaluation timeframe is used for query alerts, and 24 hours is used for service checks.

notification_preset_name

enum

Toggles the display of additional content sent in the monitor notification. Allowed enum values: show_all,hide_query,hide_handles,hide_all

default: show_all

notify_audit

boolean

A Boolean indicating whether tagged users is notified on changes to this monitor.

notify_by

[string]

Controls what granularity a monitor alerts on. Only available for monitors with groupings. For instance, a monitor grouped by cluster, namespace, and pod can be configured to only notify on each new cluster violating the alert conditions by setting notify_by to ["cluster"]. Tags mentioned in notify_by must be a subset of the grouping tags in the query. For example, a query grouped by cluster and namespace cannot notify on region. Setting notify_by to [*] configures the monitor to notify as a simple-alert.

notify_no_data

boolean

A Boolean indicating whether this monitor notifies when data stops reporting. Defaults to false.

on_missing_data

enum

Controls how groups or monitors are treated if an evaluation does not return any data points. The default option results in different behavior depending on the monitor query type. For monitors using Count queries, an empty monitor evaluation is treated as 0 and is compared to the threshold conditions. For monitors using any query type other than Count, for example Gauge, Measure, or Rate, the monitor shows the last known status. This option is only available for APM Trace Analytics, Audit Trail, CI, Error Tracking, Event, Logs, and RUM monitors. Allowed enum values: default,show_no_data,show_and_notify_no_data,resolve

renotify_interval

int64

The number of minutes after the last notification before a monitor re-notifies on the current status. It only re-notifies if it’s not resolved.

renotify_occurrences

int64

The number of times re-notification messages should be sent on the current status at the provided re-notification interval.

renotify_statuses

[string]

The types of monitor statuses for which re-notification messages are sent. Default: null if renotify_interval is null. If renotify_interval is set, defaults to renotify on Alert and No Data.

require_full_window

boolean

A Boolean indicating whether this monitor needs a full window of data before it’s evaluated. We highly recommend you set this to false for sparse metrics, otherwise some evaluations are skipped. Default is false. This setting only applies to metric monitors.

scheduling_options

object

Configuration options for scheduling.

custom_schedule

object

Configuration options for the custom schedule. This feature is in private beta.

recurrences

[object]

Array of custom schedule recurrences.

rrule

string

Defines the recurrence rule (RRULE) for a given schedule.

start

string

Defines the start date and time of the recurring schedule.

timezone

string

Defines the timezone the schedule runs on.

evaluation_window

object

Configuration options for the evaluation window. If hour_starts is set, no other fields may be set. Otherwise, day_starts and month_starts must be set together.

day_starts

string

The time of the day at which a one day cumulative evaluation window starts. Must be defined in UTC time in HH:mm format.

hour_starts

int32

The minute of the hour at which a one hour cumulative evaluation window starts.

month_starts

int32

The day of the month at which a one month cumulative evaluation window starts.

silenced

object

DEPRECATED: Information about the downtime applied to the monitor. Only shows v1 downtimes.

<any-key>

int64

UTC epoch timestamp in seconds when the downtime for the group expires.

synthetics_check_id

string

DEPRECATED: ID of the corresponding Synthetic check.

threshold_windows

object

Alerting time window options.

recovery_window

string

Describes how long an anomalous metric must be normal before the alert recovers.

trigger_window

string

Describes how long a metric must be anomalous before an alert triggers.

thresholds

object

List of the different monitor threshold available.

critical

double

The monitor CRITICAL threshold.

critical_recovery

double

The monitor CRITICAL recovery threshold.

ok

double

The monitor OK threshold.

unknown

double