Logs

Logs

Envoyez vos logs à votre plateforme Datadog via HTTP. Les limites par requête HTTP sont les suivantes :

  • Taille maximale du contenu par charge utile : 5 Mo
  • Taille maximale d’un log : 256 Ko
  • Taille maximale d’un tableau en cas d’envoi de plusieurs logs dans un tableau : 500 entrées

Tous les logs dépassant 256 Ko sont acceptés et tronqués par Datadog :

  • Pour une requête avec un seul log, l’API réduit le log de façon à ce qu’il fasse 256 Ko et renvoie un code 2xx.
  • Pour une requête avec plusieurs logs, l’API traite tous les logs, réduit uniquement les logs dépassant 256 Ko et renvoie un code 2xx.

Nous vous conseillons de compresser vos logs avant de les envoyer. Ajoutez l’en-tête Content-Encoding: gzip à la requête pour envoyer vos logs compressés.

POST https://api.datadoghq.eu/api/v2/logs/analytics/aggregatehttps://api.ddog-gov.com/api/v2/logs/analytics/aggregatehttps://api.datadoghq.com/api/v2/logs/analytics/aggregatehttps://api.us3.datadoghq.com/api/v2/logs/analytics/aggregate

Présentation

The API endpoint to aggregate events into buckets and compute metrics and timeseries.

Requête

Body Data (required)

Expand All

Champ

Type

Description

compute

[object]

The list of metrics or timeseries to compute for the retrieved buckets.

aggregation [required]

enum

An aggregation function Allowed enum values: count,cardinality,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

interval

string

The time buckets' size (only used for type=timeseries) Defaults to a resolution of 150 points

metric

string

The metric to use

type

enum

The type of compute Allowed enum values: timeseries,total

filter

object

The search and filter query settings

from

string

The minimum time for the requested logs, supports date math and regular timestamps

indexes

[string]

For customers with multiple indexes, the indexes to search. Defaults to ['*'] which means all indexes.

query

string

The search query - following the log search syntax.

to

string

The maximum time for the requested logs, supports date math and regular timestamps

group_by

[object]

The rules for the group by

facet [required]

string

The name of the facet to use (required)

histogram

object

Used to perform a histogram computation (only for measure facets). Note: At most 100 buckets are allowed, the number of buckets is (max - min)/interval.

interval [required]

double

The bin size of the histogram buckets

max [required]

double

The maximum value for the measure used in the histogram (values greater than this one are filtered out)

min [required]

double

The minimum value for the measure used in the histogram (values smaller than this one are filtered out)

limit

int64

The maximum buckets to return for this group by

missing

 <oneOf>

The value to use for logs that don't have the facet used to group by

Option 1

string

The missing value to use if there is string valued facet.

Option 2

double

The missing value to use if there is a number valued facet.

sort

object

A sort rule

aggregation

enum

An aggregation function Allowed enum values: count,cardinality,pc75,pc90,pc95,pc98,pc99,sum,min,max,avg

metric

string

The metric to sort by (only used for type=measure)

order

enum

The order to use, ascending or descending Allowed enum values: asc,desc

type

enum

The type of sorting algorithm Allowed enum values: alphabetical,measure

total

 <oneOf>

A resulting object to put the given computes in over all the matching records.

Option 1

boolean

If set to true, creates an additional bucket labeled "$facet_total"

Option 2

string

A string to use as the key value for the total bucket

Option 3

double

A number to use as the key value for the total bucket

options

object

Global query options that are used during the query. Note: You should only supply timezone or time offset but not both otherwise the query will fail.

timeOffset

int64

The time offset (in seconds) to apply to the query.

timezone

string

The timezone can be specified both as an offset, for example: "UTC+03:00".

page

object

Paging settings

cursor

string

The returned paging point to use to get the next results

{
  "compute": [
    {
      "aggregation": "pc90",
      "interval": "5m",
      "metric": "@duration",
      "type": "string"
    }
  ],
  "filter": {
    "from": "now-15m",
    "indexes": [
      "main",
      "web"
    ],
    "query": "service:web* AND @http.status_code:[200 TO 299]",
    "to": "now"
  },
  "group_by": [
    {
      "facet": "host",
      "histogram": {
        "interval": 10,
        "max": 100,
        "min": 50
      },
      "limit": "integer",
      "missing": {
        "description": "undefined",
        "type": "undefined"
      },
      "sort": {
        "aggregation": "pc90",
        "metric": "@duration",
        "order": "asc",
        "type": "string"
      },
      "total": {
        "description": "undefined",
        "type": "undefined"
      }
    }
  ],
  "options": {
    "timeOffset": "integer",
    "timezone": "GMT"
  },
  "page": {
    "cursor": "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
  }
}

Réponse

OK

The response object for the logs aggregate API endpoint

Expand All

Champ

Type

Description

data

object

The query results

buckets

[object]

The list of matching buckets, one item per bucket

by

object

The key, value pairs for each group by

<any-key>

string

The values for each group by

computes

object

A map of the metric name -> value for regular compute or list of values for a timeseries

<any-key>

 <oneOf>

A bucket value, can be either a timeseries or a single value

Option 1

string

A single string value

Option 2

double

A single number value

Option 3

[object]

A timeseries array

time

string

The time value for this point

value

double

The value for this point

meta

object

The metadata associated with a request

elapsed

int64

The time elapsed in milliseconds

page

object

Paging attributes.

after

string

The cursor to use to get the next results, if any. To make the next request, use the same. parameters with the addition of the page[cursor].

request_id

string

The identifier of the request

status

enum

The status of the response Allowed enum values: done,timeout

warnings

[object]

A list of warnings (non fatal errors) encountered, partial results might be returned if warnings are present in the response.

code

string

A unique code for this type of warning

detail

string

A detailed explanation of this specific warning

title

string

A short human-readable summary of the warning

{
  "data": {
    "buckets": [
      {
        "by": {
          "<any-key>": "string"
        },
        "computes": {
          "<any-key>": {
            "description": "undefined",
            "type": "undefined"
          }
        }
      }
    ]
  },
  "meta": {
    "elapsed": 132,
    "page": {
      "after": "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
    },
    "request_id": "MWlFUjVaWGZTTTZPYzM0VXp1OXU2d3xLSVpEMjZKQ0VKUTI0dEYtM3RSOFVR",
    "status": "done",
    "warnings": [
      {
        "code": "unknown_index",
        "detail": "indexes: foo, bar",
        "title": "One or several indexes are missing or invalid, results hold data from the other indexes"
      }
    ]
  }
}

Bad Request

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Not Authorized

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Exemple de code


# Curl command
curl -X POST "https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com/api/v2/logs/analytics/aggregate" \
-H "Content-Type: application/json" \
-H "DD-API-KEY: ${DD_API_KEY}" \
-H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \
-d @- << EOF
{
  "compute": [
    {
      "aggregation": "pc90"
    }
  ],
  "group_by": [
    {
      "facet": "host",
      "histogram": {
        "interval": 10,
        "max": 100,
        "min": 50
      }
    }
  ]
}
EOF
package main

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

func main() {
    ctx := datadog.NewDefaultContext(context.Background())

    body := *datadog.NewLogsAggregateRequest() // LogsAggregateRequest | 

    configuration := datadog.NewConfiguration()

    apiClient := datadog.NewAPIClient(configuration)
    resp, r, err := apiClient.LogsApi.AggregateLogs(ctx, body)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.AggregateLogs`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `AggregateLogs`: LogsAggregateResponse
    responseContent, _ := json.MarshalIndent(resp, "", "  ")
    fmt.Fprintf(os.Stdout, "Response from LogsApi.AggregateLogs:\n%s\n", responseContent)
}

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" go run "main.go"
import os
from dateutil.parser import parse as dateutil_parser
from datadog_api_client.v2 import ApiClient, ApiException, Configuration
from datadog_api_client.v2.api import logs_api
from datadog_api_client.v2.models import *
from pprint import pprint
# See configuration.py for a list of all supported configuration parameters.
configuration = Configuration()

# Enter a context with an instance of the API client
with ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = logs_api.LogsApi(api_client)
    body = LogsAggregateRequest(
        compute=[
            LogsCompute(
                aggregation=LogsAggregationFunction("pc90"),
                interval="5m",
                metric="@duration",
                type=LogsComputeType("total"),
            ),
        ],
        filter=LogsQueryFilter(
            _from="now-15m",
            indexes=["main","web"],
            query="service:web* AND @http.status_code:[200 TO 299]",
            to="now",
        ),
        group_by=[
            LogsGroupBy(
                facet="host",
                histogram=LogsGroupByHistogram(
                    interval=10,
                    max=100,
                    min=50,
                ),
                limit=10,
                missing=LogsGroupByMissing(),
                sort=LogsAggregateSort(
                    aggregation=LogsAggregationFunction("pc90"),
                    metric="@duration",
                    order=LogsSortOrder("asc"),
                    type=LogsAggregateSortType("alphabetical"),
                ),
                total=LogsGroupByTotal(),
            ),
        ],
        options=LogsQueryOptions(
            time_offset=1,
            timezone="GMT",
        ),
        page=LogsAggregateRequestPage(
            cursor="eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
        ),
    )  # LogsAggregateRequest | 

    # example passing only required values which don't have defaults set
    try:
        # Aggregate events
        api_response = api_instance.aggregate_logs(body)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->aggregate_logs: %s\n" % e)

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" python3 "example.py"
require 'datadog_api_client'
api_instance = DatadogAPIClient::V2::LogsAPI.new
body = DatadogAPIClient::V2::LogsAggregateRequest.new # LogsAggregateRequest | 

begin
  # Aggregate events
  result = api_instance.aggregate_logs(body)
  p result
rescue DatadogAPIClient::V2::APIError => e
  puts "Error when calling LogsAPI->aggregate_logs: #{e}"
end

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" rb "example.rb"
import { v2 } from "@datadog/datadog-api-client";
import * as fs from "fs";

const configuration = v2.createConfiguration();
const apiInstance = new v2.LogsApi(configuration);

let params: v2.LogsApiAggregateLogsRequest = {
  // LogsAggregateRequest
  body: {
    compute: [
      {
        aggregation: "pc90",
        interval: "5m",
        metric: "@duration",
        type: "total",
      },
    ],
    filter: {
      from: "now-15m",
      indexes: ["main", "web"],
      query: "service:web* AND @http.status_code:[200 TO 299]",
      to: "now",
    },
    groupBy: [
      {
        facet: "host",
        histogram: {
          interval: 10,
          max: 100,
          min: 50,
        },
        limit: 10,
        missing: "string_example",
        sort: {
          aggregation: "pc90",
          metric: "@duration",
          order: "asc",
          type: "alphabetical",
        },
        total: true,
      },
    ],
    options: {
      timeOffset: 1,
      timezone: "GMT",
    },
    page: {
      cursor:
        "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
    },
  },
};

apiInstance
  .aggregateLogs(params)
  .then((data: any) => {
    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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" tsc "example.ts"
import java.util.*;
import com.datadog.api.v2.client.ApiClient;
import com.datadog.api.v2.client.ApiException;
import com.datadog.api.v2.client.Configuration;
import com.datadog.api.v2.client.model.*;
import com.datadog.api.v2.client.api.LogsApi;

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

        LogsApi apiInstance = new LogsApi(defaultClient);
        LogsAggregateRequest body = new LogsAggregateRequest(); // LogsAggregateRequest | 
        try {
            LogsAggregateResponse result = apiInstance.aggregateLogs(body);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling LogsApi#aggregateLogs");
            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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" java "Example.java"

POST https://api.datadoghq.eu/api/v1/logs-queries/listhttps://api.ddog-gov.com/api/v1/logs-queries/listhttps://api.datadoghq.com/api/v1/logs-queries/listhttps://api.us3.datadoghq.com/api/v1/logs-queries/list

Présentation

Cet endpoint renvoie les logs qui correspondent à une requête de recherche de logs. Les résultats sont paginés.

Si vous songez à archiver les logs de votre organisation, nous vous conseillons d’utiliser les fonctionnalités d’archivage de Datadog plutôt que l’API Log List. Consultez la documentation sur l’archivage de logs Datadog.

Requête

Body Data (required)

Filtre de logs

Expand All

Champ

Type

Description

index

string

The log index on which the request is performed. For multi-index organizations, the default is all live indexes. Historical indexes of rehydrated logs must be specified.

limit

int32

Number of logs return in the response.

query

string

The search query - following the log search syntax.

sort

enum

Time-ascending asc or time-descending descresults. Allowed enum values: asc,desc

startAt

string

Hash identifier of the first log to return in the list, available in a log id attribute. This parameter is used for the pagination feature.

Note: This parameter is ignored if the corresponding log is out of the scope of the specified time window.

time [required]

object

Timeframe to retrieve the log from.

from [required]

date-time

Minimum timestamp for requested logs.

timezone

string

Timezone can be specified both as an offset (e.g. "UTC+03:00") or a regional zone (e.g. "Europe/Paris").

to [required]

date-time

Maximum timestamp for requested logs.

{
  "index": "retention-3,retention-15",
  "limit": "integer",
  "query": "service:web* AND @http.status_code:[200 TO 299]",
  "sort": "string",
  "startAt": "string",
  "time": {
    "from": "2020-02-02T02:02:02Z",
    "timezone": "string",
    "to": "2020-02-02T20:20:20Z"
  }
}

Réponse

OK

Response object with all logs matching the request and pagination information.

Expand All

Champ

Type

Description

logs

[object]

Array of logs matching the request and the nextLogId if sent.

content

object

JSON object containing all log attributes and their associated values.

attributes

object

JSON object of attributes from your log.

host

string

Name of the machine from where the logs are being sent.

message

string

The message reserved attribute of your log. By default, Datadog ingests the value of the message attribute as the body of the log entry. That value is then highlighted and displayed in the Logstream, where it is indexed for full text search.

service

string

The name of the application or service generating the log events. It is used to switch from Logs to APM, so make sure you define the same value when you use both products.

tags

array

Array of tags associated with your log.

timestamp

date-time

Timestamp of your log.

id

string

Unique ID of the Log.

nextLogId

string

Hash identifier of the next log to return in the list. This parameter is used for the pagination feature.

status

string

Status of the response.

{
  "logs": [
    {
      "content": {
        "attributes": [
          {}
        ],
        "host": "i-0123",
        "message": "Host connected to remote",
        "service": "agent",
        "tags": [
          "team:A"
        ],
        "timestamp": "2020-05-26T13:36:14Z"
      },
      "id": "AAAAAWgN8Xwgr1vKDQAAAABBV2dOOFh3ZzZobm1mWXJFYTR0OA"
    }
  ],
  "nextLogId": "string",
  "status": "string"
}

Bad Request

Response returned by the Logs API when errors occur.

Expand All

Champ

Type

Description

error

object

Error returned by the Logs API

code

string

Code identifying the error

details

[object]

Additional error details

message

string

Error message

{
  "error": {
    "code": "string",
    "details": [],
    "message": "string"
  }
}

Authentication error

Error response object.

Expand All

Champ

Type

Description

errors [required]

[string]

Array of errors returned by the API.

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

Exemple de code


# Curl command
curl -X POST "https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com/api/v1/logs-queries/list" \
-H "Content-Type: application/json" \
-H "DD-API-KEY: ${DD_API_KEY}" \
-H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \
-d @- << EOF
{
  "time": {
    "from": "2020-02-02T02:02:02Z",
    "to": "2020-02-02T20:20:20Z"
  }
}
EOF
package main

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

func main() {
    ctx := datadog.NewDefaultContext(context.Background())

    body := *datadog.NewLogsListRequest(*datadog.NewLogsListRequestTime(time.Now(), time.Now())) // LogsListRequest | Logs filter

    configuration := datadog.NewConfiguration()

    apiClient := datadog.NewAPIClient(configuration)
    resp, r, err := apiClient.LogsApi.ListLogs(ctx, body)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.ListLogs`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `ListLogs`: LogsListResponse
    responseContent, _ := json.MarshalIndent(resp, "", "  ")
    fmt.Fprintf(os.Stdout, "Response from LogsApi.ListLogs:\n%s\n", responseContent)
}

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" go run "main.go"
import os
from dateutil.parser import parse as dateutil_parser
from datadog_api_client.v1 import ApiClient, ApiException, Configuration
from datadog_api_client.v1.api import logs_api
from datadog_api_client.v1.models import *
from pprint import pprint
# See configuration.py for a list of all supported configuration parameters.
configuration = Configuration()

# Enter a context with an instance of the API client
with ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = logs_api.LogsApi(api_client)
    body = LogsListRequest(
        index="retention-3,retention-15",
        limit=1,
        query="service:web* AND @http.status_code:[200 TO 299]",
        sort=LogsSort("asc"),
        start_at="start_at_example",
        time=LogsListRequestTime(
            _from=dateutil_parser('2020-02-02T02:02:02Z'),
            timezone="timezone_example",
            to=dateutil_parser('2020-02-02T20:20:20Z'),
        ),
    )  # LogsListRequest | Logs filter

    # example passing only required values which don't have defaults set
    try:
        # Search logs
        api_response = api_instance.list_logs(body)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->list_logs: %s\n" % e)

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" python3 "example.py"
require 'datadog_api_client'
api_instance = DatadogAPIClient::V1::LogsAPI.new
body = DatadogAPIClient::V1::LogsListRequest.new({time: DatadogAPIClient::V1::LogsListRequestTime.new({from: Time.parse('2020-02-02T02:02:02Z'), to: Time.parse('2020-02-02T20:20:20Z')})}) # LogsListRequest | Logs filter

begin
  # Search logs
  result = api_instance.list_logs(body)
  p result
rescue DatadogAPIClient::V1::APIError => e
  puts "Error when calling LogsAPI->list_logs: #{e}"
end

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" rb "example.rb"
import { v1 } from "@datadog/datadog-api-client";
import * as fs from "fs";

const configuration = v1.createConfiguration();
const apiInstance = new v1.LogsApi(configuration);

let params: v1.LogsApiListLogsRequest = {
  // LogsListRequest | Logs filter
  body: {
    index: "retention-3,retention-15",
    limit: 1,
    query: "service:web* AND @http.status_code:[200 TO 299]",
    sort: "asc",
    startAt: "startAt_example",
    time: {
      from: new Date("2020-02-02T02:02:02Z"),
      timezone: "timezone_example",
      to: new Date("2020-02-02T20:20:20Z"),
    },
  },
};

apiInstance
  .listLogs(params)
  .then((data: any) => {
    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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" tsc "example.ts"
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.LogsApi;

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

        LogsApi apiInstance = new LogsApi(defaultClient);
        LogsListRequest body = new LogsListRequest(); // LogsListRequest | Logs filter
        try {
            LogsListResponse result = apiInstance.listLogs(body);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling LogsApi#listLogs");
            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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" java "Example.java"

POST https://api.datadoghq.eu/api/v2/logs/events/searchhttps://api.ddog-gov.com/api/v2/logs/events/searchhttps://api.datadoghq.com/api/v2/logs/events/searchhttps://api.us3.datadoghq.com/api/v2/logs/events/search

Présentation

Cet endpoint renvoie les logs qui correspondent à une requête de recherche de logs. Les résultats sont paginés.

Si vous songez à archiver les logs de votre organisation, nous vous conseillons d’utiliser les fonctionnalités d’archivage de Datadog plutôt que l’API Log List. Consultez la documentation sur l’archivage de logs Datadog.

Requête

Body Data

Filtre de logs

Expand All

Champ

Type

Description

filter

object

The search and filter query settings

from

string

The minimum time for the requested logs, supports date math and regular timestamps

indexes

[string]

For customers with multiple indexes, the indexes to search. Defaults to ['*'] which means all indexes.

query

string

The search query - following the log search syntax.

to

string

The maximum time for the requested logs, supports date math and regular timestamps

options

object

Global query options that are used during the query. Note: You should only supply timezone or time offset but not both otherwise the query will fail.

timeOffset

int64

The time offset (in seconds) to apply to the query.

timezone

string

The timezone can be specified both as an offset, for example: "UTC+03:00".

page

object

Paging attributes for listing logs.

cursor

string

List following results with a cursor provided in the previous query.

limit

int32

Maximum number of logs in the response.

sort

enum

Sort parameters when querying logs. Allowed enum values: timestamp,-timestamp

{
  "filter": {
    "from": "now-15m",
    "indexes": [
      "main",
      "web"
    ],
    "query": "service:web* AND @http.status_code:[200 TO 299]",
    "to": "now"
  },
  "options": {
    "timeOffset": "integer",
    "timezone": "GMT"
  },
  "page": {
    "cursor": "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
    "limit": 25
  },
  "sort": "string"
}

Réponse

OK

Response object with all logs matching the request and pagination information.

Expand All

Champ

Type

Description

data

[object]

Array of logs matching the request.

attributes

object

JSON object containing all log attributes and their associated values.

attributes

object

JSON object of attributes from your log.

host

string

Name of the machine from where the logs are being sent.

message

string

The message reserved attribute of your log. By default, Datadog ingests the value of the message attribute as the body of the log entry. That value is then highlighted and displayed in the Logstream, where it is indexed for full text search.

service

string

The name of the application or service generating the log events. It is used to switch from Logs to APM, so make sure you define the same value when you use both products.

status

string

Status of the message associated with your log.

tags

[string]

Array of tags associated with your log.

timestamp

date-time

Timestamp of your log.

id

string

Unique ID of the Log.

type

enum

Type of the event. Allowed enum values: log

links

object

Links attributes.

next

string

Link for the next set of results. Note that the request can also be made using the POST endpoint.

meta

object

The metadata associated with a request

elapsed

int64

The time elapsed in milliseconds

page

object

Paging attributes.

after

string

The cursor to use to get the next results, if any. To make the next request, use the same. parameters with the addition of the page[cursor].

request_id

string

The identifier of the request

status

enum

The status of the response Allowed enum values: done,timeout

warnings

[object]

A list of warnings (non fatal errors) encountered, partial results might be returned if warnings are present in the response.

code

string

A unique code for this type of warning

detail

string

A detailed explanation of this specific warning

title

string

A short human-readable summary of the warning

{
  "data": [
    {
      "attributes": {
        "attributes": [
          {}
        ],
        "host": "i-0123",
        "message": "Host connected to remote",
        "service": "agent",
        "status": "INFO",
        "tags": [
          "team:A"
        ],
        "timestamp": "2019-01-02T09:42:36.320Z"
      },
      "id": "AAAAAWgN8Xwgr1vKDQAAAABBV2dOOFh3ZzZobm1mWXJFYTR0OA",
      "type": "log"
    }
  ],
  "links": {
    "next": "https://app.datadoghq.com/api/v2/logs/event?filter[query]=foo\u0026page[cursor]=eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
  },
  "meta": {
    "elapsed": 132,
    "page": {
      "after": "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
    },
    "request_id": "MWlFUjVaWGZTTTZPYzM0VXp1OXU2d3xLSVpEMjZKQ0VKUTI0dEYtM3RSOFVR",
    "status": "done",
    "warnings": [
      {
        "code": "unknown_index",
        "detail": "indexes: foo, bar",
        "title": "One or several indexes are missing or invalid, results hold data from the other indexes"
      }
    ]
  }
}

Bad Request

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Not Authorized

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Exemple de code


# Curl command
curl -X POST "https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com/api/v2/logs/events/search" \
-H "Content-Type: application/json" \
-H "DD-API-KEY: ${DD_API_KEY}" \
-H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \
-d @- << EOF
{}
EOF
package main

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

func main() {
    ctx := datadog.NewDefaultContext(context.Background())

    body := *datadog.NewLogsListRequest() // LogsListRequest |  (optional)
    optionalParams := datadog.ListLogsOptionalParameters{
        Body: &body,
    }

    configuration := datadog.NewConfiguration()

    apiClient := datadog.NewAPIClient(configuration)
    resp, r, err := apiClient.LogsApi.ListLogs(ctx, optionalParams)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.ListLogs`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `ListLogs`: LogsListResponse
    responseContent, _ := json.MarshalIndent(resp, "", "  ")
    fmt.Fprintf(os.Stdout, "Response from LogsApi.ListLogs:\n%s\n", responseContent)
}

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" go run "main.go"
import os
from dateutil.parser import parse as dateutil_parser
from datadog_api_client.v2 import ApiClient, ApiException, Configuration
from datadog_api_client.v2.api import logs_api
from datadog_api_client.v2.models import *
from pprint import pprint
# See configuration.py for a list of all supported configuration parameters.
configuration = Configuration()

# Enter a context with an instance of the API client
with ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = logs_api.LogsApi(api_client)
    body = LogsListRequest(
        filter=LogsQueryFilter(
            _from="now-15m",
            indexes=["main","web"],
            query="service:web* AND @http.status_code:[200 TO 299]",
            to="now",
        ),
        options=LogsQueryOptions(
            time_offset=1,
            timezone="GMT",
        ),
        page=LogsListRequestPage(
            cursor="eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
            limit=25,
        ),
        sort=LogsSort("timestamp"),
    )  # LogsListRequest |  (optional)

    # example passing only required values which don't have defaults set
    # and optional values
    try:
        # Search logs
        api_response = api_instance.list_logs(body=body)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->list_logs: %s\n" % e)

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" python3 "example.py"
require 'datadog_api_client'
api_instance = DatadogAPIClient::V2::LogsAPI.new
opts = {
  body: DatadogAPIClient::V2::LogsListRequest.new # LogsListRequest | 
}

begin
  # Search logs
  result = api_instance.list_logs(opts)
  p result
rescue DatadogAPIClient::V2::APIError => e
  puts "Error when calling LogsAPI->list_logs: #{e}"
end

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" rb "example.rb"
import { v2 } from "@datadog/datadog-api-client";
import * as fs from "fs";

const configuration = v2.createConfiguration();
const apiInstance = new v2.LogsApi(configuration);

let params: v2.LogsApiListLogsRequest = {
  // LogsListRequest (optional)
  body: {
    filter: {
      from: "now-15m",
      indexes: ["main", "web"],
      query: "service:web* AND @http.status_code:[200 TO 299]",
      to: "now",
    },
    options: {
      timeOffset: 1,
      timezone: "GMT",
    },
    page: {
      cursor:
        "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
      limit: 25,
    },
    sort: "timestamp",
  },
};

apiInstance
  .listLogs(params)
  .then((data: any) => {
    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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" tsc "example.ts"
import java.util.*;
import com.datadog.api.v2.client.ApiClient;
import com.datadog.api.v2.client.ApiException;
import com.datadog.api.v2.client.Configuration;
import com.datadog.api.v2.client.model.*;
import com.datadog.api.v2.client.api.LogsApi;

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

        LogsApi apiInstance = new LogsApi(defaultClient);
        LogsListRequest body = new LogsListRequest(); // LogsListRequest | 
        try {
            LogsListResponse result = apiInstance.listLogs(new LogsApi.ListLogsOptionalParameters()
                .body(body));
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling LogsApi#listLogs");
            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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" java "Example.java"

POST https://http-intake.logs.datadoghq.eu/v1/inputhttps://http-intake.logs.ddog-gov.com/v1/inputhttps://http-intake.logs.datadoghq.com/v1/inputhttps://http-intake.logs.us3.datadoghq.com/v1/input

Présentation

Envoyez vos logs à votre plate-forme Datadog via HTTP. Les limites par requête HTTP sont les suivantes :

  • Taille maximale du contenu par charge utile (sans compression) : 5 Mo
  • Taille maximale d’un log : 1 Mo
  • Taille maximale d’un tableau en cas d’envoi de plusieurs logs dans un tableau : 1 000 entrées

Tous les logs dépassant 1 Mo sont acceptés et tronqués par Datadog :

  • Pour une requête avec un seul log, l’API réduit le log de façon à ce qu’il fasse 1 Mo et renvoie un code 2xx.
  • Pour une requête avec plusieurs logs, l’API traite tous les logs, réduit uniquement les logs dépassant 1 Mo et renvoie un code 2xx.

Nous vous conseillons de compresser vos logs avant de les envoyer. Ajoutez l’en-tête Content-Encoding: gzip à la requête pour envoyer vos logs compressés.

Voici les différents codes de statut renvoyés par l’API HTTP :

  • 200: OK
  • 400: Bad request (probablement une erreur dans la mise en forme de la charge utile)
  • 403: Permission issue (probablement une clé d’API non valide)
  • 413: Payload too large (taille du lot supérieure à 5 Mo une fois décompressé)
  • 5xx: Internal error (la requête sera renvoyée ultérieurement)

Arguments

Chaînes de requête

Nom

Type

Description

ddtags

string

Log tags can be passed as query parameters with text/plain content type.

Paramètres d'en-tête

Nom

Type

Description

Content-Encoding

string

HTTP header used to compress the media-type.

Requête

Body Data (required)

Log à envoyer (format JSON).

Expand All

Champ

Type

Description

ddsource

string

The integration name associated with your log: the technology from which the log originated. When it matches an integration name, Datadog automatically installs the corresponding parsers and facets. See reserved attributes.

ddtags

string

Tags associated with your logs.

hostname

string

The name of the originating host of the log.

message

string

The message reserved attribute of your log. By default, Datadog ingests the value of the message attribute as the body of the log entry. That value is then highlighted and displayed in the Logstream, where it is indexed for full text search.

service

string

The name of the application or service generating the log events. It is used to switch from Logs to APM, so make sure you define the same value when you use both products. See reserved attributes.

{
  "ddsource": "nginx",
  "ddtags": "env:staging,version:5.1",
  "hostname": "i-012345678",
  "message": "2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
  "service": "payment"
}

Réponse

Response from server (always 200 empty JSON).

Expand All

Champ

Type

Description

No response body

{}

unexpected error

Invalid query performed.

Expand All

Champ

Type

Description

code [required]

int32

Error code.

message [required]

string

Error message.

{
  "code": 0,
  "message": "Your browser sent an invalid request."
}

Exemple de code


## Multi JSON Messages
# Pass multiple log objects at once.
# Curl command
curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \
-H "Content-Type: application/json" \
-H "DD-API-KEY: ${DD_API_KEY}" \
-d @- << EOF
[
  {
    "message": "hello"
  },
  {
    "message": "world"
  }
]
EOF
## Simple JSON Message # Log attributes can be passed as `key:value` pairs in valid JSON messages. # Curl command curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -d @- << EOF { "ddsource": "agent", "ddtags": "env:prod,user:joe.doe", "hostname": "fa1e1e739d95", "message": "hello world" } EOF
## Multi Logplex Messages # Submit log messages. # Curl command curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \ -H "Content-Type: application/logplex-1" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -d @- << EOF hello world EOF
## Simple Logplex Message # Submit log string. # Curl command curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \ -H "Content-Type: application/logplex-1" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -d @- << EOF hello world EOF
## Multi Raw Messages # Submit log string. # Curl command curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \ -H "Content-Type: text/plain" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -d @- << EOF hello world EOF
## Simple Raw Message # Submit log string. Log attributes can be passed as query parameters in the URL. This enables the addition of tags or the source by using the `ddtags` and `ddsource` parameters: `?host=my-hostname&service=my-service&ddsource=my-source&ddtags=env:prod,user:my-user`. # Curl command curl -X POST "https://http-intake.logs.datadoghq.eu"https://http-intake.logs.ddog-gov.com"https://http-intake.logs.datadoghq.com"https://http-intake.logs.us3.datadoghq.com/v1/input" \ -H "Content-Type: text/plain" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -d @- << EOF hello world EOF
package main

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

func main() {
    ctx := datadog.NewDefaultContext(context.Background())

    body := []datadog.HTTPLogItem{*datadog.NewHTTPLogItem()} // []HTTPLogItem | Log to send (JSON format).
    contentEncoding := datadog.ContentEncoding("gzip") // ContentEncoding | HTTP header used to compress the media-type. (optional)
    ddtags := "env:prod,user:my-user" // string | Log tags can be passed as query parameters with `text/plain` content type. (optional)
    optionalParams := datadog.SubmitLogOptionalParameters{
        ContentEncoding: &contentEncoding,
        Ddtags: &ddtags,
    }

    configuration := datadog.NewConfiguration()

    apiClient := datadog.NewAPIClient(configuration)
    resp, r, err := apiClient.LogsApi.SubmitLog(ctx, body, optionalParams)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.SubmitLog`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `SubmitLog`: interface{}
    responseContent, _ := json.MarshalIndent(resp, "", "  ")
    fmt.Fprintf(os.Stdout, "Response from LogsApi.SubmitLog:\n%s\n", responseContent)
}

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" go run "main.go"
import os
from dateutil.parser import parse as dateutil_parser
from datadog_api_client.v1 import ApiClient, ApiException, Configuration
from datadog_api_client.v1.api import logs_api
from datadog_api_client.v1.models import *
from pprint import pprint
# See configuration.py for a list of all supported configuration parameters.
configuration = Configuration()

# Enter a context with an instance of the API client
with ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = logs_api.LogsApi(api_client)
    body = HTTPLog([
        HTTPLogItem(
            ddsource="nginx",
            ddtags="env:staging,version:5.1",
            hostname="i-012345678",
            message="2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
            service="payment",
        ),
    ])  # HTTPLog | Log to send (JSON format).
    content_encoding = ContentEncoding("gzip")  # ContentEncoding | HTTP header used to compress the media-type. (optional)
    ddtags = "env:prod,user:my-user"  # str | Log tags can be passed as query parameters with `text/plain` content type. (optional)

    # example passing only required values which don't have defaults set
    try:
        # Send logs
        api_response = api_instance.submit_log(body)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->submit_log: %s\n" % e)

    # example passing only required values which don't have defaults set
    # and optional values
    try:
        # Send logs
        api_response = api_instance.submit_log(body, content_encoding=content_encoding, ddtags=ddtags)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->submit_log: %s\n" % e)

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" python3 "example.py"
require 'datadog_api_client'
api_instance = DatadogAPIClient::V1::LogsAPI.new
body = [DatadogAPIClient::V1::HTTPLogItem.new] # Array<HTTPLogItem> | Log to send (JSON format).
opts = {
  content_encoding: DatadogAPIClient::V1::ContentEncoding::gzip, # ContentEncoding | HTTP header used to compress the media-type.
  ddtags: 'env:prod,user:my-user' # String | Log tags can be passed as query parameters with `text/plain` content type.
}

begin
  # Send logs
  result = api_instance.submit_log(body, opts)
  p result
rescue DatadogAPIClient::V1::APIError => e
  puts "Error when calling LogsAPI->submit_log: #{e}"
end

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" rb "example.rb"
import { v1 } from "@datadog/datadog-api-client";
import * as fs from "fs";

const configuration = v1.createConfiguration();
const apiInstance = new v1.LogsApi(configuration);

let params: v1.LogsApiSubmitLogRequest = {
  // Array<HTTPLogItem> | Log to send (JSON format).
  body: [
    {
      ddsource: "nginx",
      ddtags: "env:staging,version:5.1",
      hostname: "i-012345678",
      message: "2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
      service: "payment",
    },
    {
      ddsource: "nginx",
      ddtags: "env:staging,version:5.1",
      hostname: "i-012345678",
      message: "2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
      service: "payment",
    },
  ],
  // ContentEncoding | HTTP header used to compress the media-type. (optional)
  contentEncoding: "gzip",
  // string | Log tags can be passed as query parameters with `text/plain` content type. (optional)
  ddtags: "env:prod,user:my-user",
};

apiInstance
  .submitLog(params)
  .then((data: any) => {
    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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" tsc "example.ts"
import java.util.*;
import com.datadog.api.v1.client.ApiClient;
import com.datadog.api.v1.client.ApiException;
import com.datadog.api.v1.client.Configuration;
import com.datadog.api.v1.client.model.*;
import com.datadog.api.v1.client.api.LogsApi;

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

        LogsApi apiInstance = new LogsApi(defaultClient);
        List<HTTPLogItem> body = Arrays.asList(); // List<HTTPLogItem> | Log to send (JSON format).
        ContentEncoding contentEncoding = ContentEncoding.fromValue("gzip"); // ContentEncoding | HTTP header used to compress the media-type.
        String ddtags = "env:prod,user:my-user"; // String | Log tags can be passed as query parameters with `text/plain` content type.
        try {
            Object result = apiInstance.submitLog(body, new LogsApi.SubmitLogOptionalParameters()
                .contentEncoding(contentEncoding)
                .ddtags(ddtags));
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling LogsApi#submitLog");
            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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" java "Example.java"

GET https://api.datadoghq.eu/api/v2/logs/eventshttps://api.ddog-gov.com/api/v2/logs/eventshttps://api.datadoghq.com/api/v2/logs/eventshttps://api.us3.datadoghq.com/api/v2/logs/events

Présentation

List endpoint returns logs that match a log search query. Results are paginated.

Use this endpoint to see your latest logs.

If you are considering archiving logs for your organization, consider use of the Datadog archive capabilities instead of the log list API. See Datadog Logs Archive documentation.

Arguments

Chaînes de requête

Nom

Type

Description

filter[query]

string

Search query following logs syntax.

filter[index]

string

For customers with multiple indexes, the indexes to search Defaults to ‘*’ which means all indexes

filter[from]

string

Minimum timestamp for requested logs.

filter[to]

string

Maximum timestamp for requested logs.

sort

string

Order of logs in results.

page[cursor]

string

List following results with a cursor provided in the previous query.

page[limit]

integer

Maximum number of logs in the response.

Réponse

OK

Response object with all logs matching the request and pagination information.

Expand All

Champ

Type

Description

data

[object]

Array of logs matching the request.

attributes

object

JSON object containing all log attributes and their associated values.

attributes

object

JSON object of attributes from your log.

host

string

Name of the machine from where the logs are being sent.

message

string

The message reserved attribute of your log. By default, Datadog ingests the value of the message attribute as the body of the log entry. That value is then highlighted and displayed in the Logstream, where it is indexed for full text search.

service

string

The name of the application or service generating the log events. It is used to switch from Logs to APM, so make sure you define the same value when you use both products.

status

string

Status of the message associated with your log.

tags

[string]

Array of tags associated with your log.

timestamp

date-time

Timestamp of your log.

id

string

Unique ID of the Log.

type

enum

Type of the event. Allowed enum values: log

links

object

Links attributes.

next

string

Link for the next set of results. Note that the request can also be made using the POST endpoint.

meta

object

The metadata associated with a request

elapsed

int64

The time elapsed in milliseconds

page

object

Paging attributes.

after

string

The cursor to use to get the next results, if any. To make the next request, use the same. parameters with the addition of the page[cursor].

request_id

string

The identifier of the request

status

enum

The status of the response Allowed enum values: done,timeout

warnings

[object]

A list of warnings (non fatal errors) encountered, partial results might be returned if warnings are present in the response.

code

string

A unique code for this type of warning

detail

string

A detailed explanation of this specific warning

title

string

A short human-readable summary of the warning

{
  "data": [
    {
      "attributes": {
        "attributes": [
          {}
        ],
        "host": "i-0123",
        "message": "Host connected to remote",
        "service": "agent",
        "status": "INFO",
        "tags": [
          "team:A"
        ],
        "timestamp": "2019-01-02T09:42:36.320Z"
      },
      "id": "AAAAAWgN8Xwgr1vKDQAAAABBV2dOOFh3ZzZobm1mWXJFYTR0OA",
      "type": "log"
    }
  ],
  "links": {
    "next": "https://app.datadoghq.com/api/v2/logs/event?filter[query]=foo\u0026page[cursor]=eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
  },
  "meta": {
    "elapsed": 132,
    "page": {
      "after": "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="
    },
    "request_id": "MWlFUjVaWGZTTTZPYzM0VXp1OXU2d3xLSVpEMjZKQ0VKUTI0dEYtM3RSOFVR",
    "status": "done",
    "warnings": [
      {
        "code": "unknown_index",
        "detail": "indexes: foo, bar",
        "title": "One or several indexes are missing or invalid, results hold data from the other indexes"
      }
    ]
  }
}

Bad Request

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Not Authorized

API error response.

Expand All

Champ

Type

Description

errors [required]

[string]

A list of errors.

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

Exemple de code


# Curl command
curl -X GET "https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com/api/v2/logs/events" \
-H "Content-Type: application/json" \
-H "DD-API-KEY: ${DD_API_KEY}" \
-H "DD-APPLICATION-KEY: ${DD_APP_KEY}"
package main

import (
    "context"
    "encoding/json"
    "fmt"
    "os"
    "time"
    datadog "github.com/DataDog/datadog-api-client-go/api/v2/datadog"
)

func main() {
    ctx := datadog.NewDefaultContext(context.Background())

    filterQuery := "@datacenter:us @role:db" // string | Search query following logs syntax. (optional)
    filterIndex := "main" // string | For customers with multiple indexes, the indexes to search Defaults to '*' which means all indexes (optional)
    filterFrom := time.Now() // time.Time | Minimum timestamp for requested logs. (optional)
    filterTo := time.Now() // time.Time | Maximum timestamp for requested logs. (optional)
    sort := datadog.LogsSort("timestamp") // LogsSort | Order of logs in results. (optional)
    pageCursor := "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==" // string | List following results with a cursor provided in the previous query. (optional)
    pageLimit := int32(25) // int32 | Maximum number of logs in the response. (optional) (default to 10)
    optionalParams := datadog.ListLogsGetOptionalParameters{
        FilterQuery: &filterQuery,
        FilterIndex: &filterIndex,
        FilterFrom: &filterFrom,
        FilterTo: &filterTo,
        Sort: &sort,
        PageCursor: &pageCursor,
        PageLimit: &pageLimit,
    }

    configuration := datadog.NewConfiguration()

    apiClient := datadog.NewAPIClient(configuration)
    resp, r, err := apiClient.LogsApi.ListLogsGet(ctx, optionalParams)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.ListLogsGet`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    // response from `ListLogsGet`: LogsListResponse
    responseContent, _ := json.MarshalIndent(resp, "", "  ")
    fmt.Fprintf(os.Stdout, "Response from LogsApi.ListLogsGet:\n%s\n", responseContent)
}

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" go run "main.go"
import os
from dateutil.parser import parse as dateutil_parser
from datadog_api_client.v2 import ApiClient, ApiException, Configuration
from datadog_api_client.v2.api import logs_api
from datadog_api_client.v2.models import *
from pprint import pprint
# See configuration.py for a list of all supported configuration parameters.
configuration = Configuration()

# Enter a context with an instance of the API client
with ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = logs_api.LogsApi(api_client)
    filter_query = "@datacenter:us @role:db"  # str | Search query following logs syntax. (optional)
    filter_index = "main"  # str | For customers with multiple indexes, the indexes to search Defaults to '*' which means all indexes (optional)
    filter_from = dateutil_parser('2019-01-02T09:42:36.320Z')  # datetime | Minimum timestamp for requested logs. (optional)
    filter_to = dateutil_parser('2019-01-03T09:42:36.320Z')  # datetime | Maximum timestamp for requested logs. (optional)
    sort = LogsSort("timestamp")  # LogsSort | Order of logs in results. (optional)
    page_cursor = "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="  # str | List following results with a cursor provided in the previous query. (optional)
    page_limit = 25  # int | Maximum number of logs in the response. (optional) if omitted the server will use the default value of 10

    # example passing only required values which don't have defaults set
    # and optional values
    try:
        # Get a list of logs
        api_response = api_instance.list_logs_get(filter_query=filter_query, filter_index=filter_index, filter_from=filter_from, filter_to=filter_to, sort=sort, page_cursor=page_cursor, page_limit=page_limit)
        pprint(api_response)
    except ApiException as e:
        print("Exception when calling LogsApi->list_logs_get: %s\n" % e)

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" python3 "example.py"
require 'datadog_api_client'
api_instance = DatadogAPIClient::V2::LogsAPI.new
opts = {
  filter_query: '@datacenter:us @role:db', # String | Search query following logs syntax.
  filter_index: 'main', # String | For customers with multiple indexes, the indexes to search Defaults to '*' which means all indexes
  filter_from: Time.parse('2019-01-02T09:42:36.320Z'), # Time | Minimum timestamp for requested logs.
  filter_to: Time.parse('2019-01-03T09:42:36.320Z'), # Time | Maximum timestamp for requested logs.
  sort: DatadogAPIClient::V2::LogsSort::TIMESTAMP_ASCENDING, # LogsSort | Order of logs in results.
  page_cursor: 'eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==', # String | List following results with a cursor provided in the previous query.
  page_limit: 25 # Integer | Maximum number of logs in the response.
}

begin
  # Get a list of logs
  result = api_instance.list_logs_get(opts)
  p result
rescue DatadogAPIClient::V2::APIError => e
  puts "Error when calling LogsAPI->list_logs_get: #{e}"
end

Instructions

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

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" rb "example.rb"
import { v2 } from "@datadog/datadog-api-client";
import * as fs from "fs";

const configuration = v2.createConfiguration();
const apiInstance = new v2.LogsApi(configuration);

let params: v2.LogsApiListLogsGetRequest = {
  // string | Search query following logs syntax. (optional)
  filterQuery: "@datacenter:us @role:db",
  // string | For customers with multiple indexes, the indexes to search Defaults to '*' which means all indexes (optional)
  filterIndex: "main",
  // Date | Minimum timestamp for requested logs. (optional)
  filterFrom: new Date("2019-01-02T09:42:36.320Z"),
  // Date | Maximum timestamp for requested logs. (optional)
  filterTo: new Date("2019-01-03T09:42:36.320Z"),
  // LogsSort | Order of logs in results. (optional)
  sort: "timestamp",
  // string | List following results with a cursor provided in the previous query. (optional)
  pageCursor:
    "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ==",
  // number | Maximum number of logs in the response. (optional)
  pageLimit: 25,
};

apiInstance
  .listLogsGet(params)
  .then((data: any) => {
    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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" tsc "example.ts"
import java.time.OffsetDateTime;
import java.util.*;
import com.datadog.api.v2.client.ApiClient;
import com.datadog.api.v2.client.ApiException;
import com.datadog.api.v2.client.Configuration;
import com.datadog.api.v2.client.model.*;
import com.datadog.api.v2.client.api.LogsApi;

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

        LogsApi apiInstance = new LogsApi(defaultClient);
        String filterQuery = "@datacenter:us @role:db"; // String | Search query following logs syntax.
        String filterIndex = "main"; // String | For customers with multiple indexes, the indexes to search Defaults to '*' which means all indexes
        OffsetDateTime filterFrom = OffsetDateTime.parse("2019-01-02T09:42:36.320Z"); // OffsetDateTime | Minimum timestamp for requested logs.
        OffsetDateTime filterTo = OffsetDateTime.parse("2019-01-03T09:42:36.320Z"); // OffsetDateTime | Maximum timestamp for requested logs.
        LogsSort sort = LogsSort.fromValue("timestamp"); // LogsSort | Order of logs in results.
        String pageCursor = "eyJzdGFydEF0IjoiQVFBQUFYS2tMS3pPbm40NGV3QUFBQUJCV0V0clRFdDZVbG8zY3pCRmNsbHJiVmxDWlEifQ=="; // String | List following results with a cursor provided in the previous query.
        Integer pageLimit = 10; // Integer | Maximum number of logs in the response.
        try {
            LogsListResponse result = apiInstance.listLogsGet(new LogsApi.ListLogsGetOptionalParameters()
                .filterQuery(filterQuery)
                .filterIndex(filterIndex)
                .filterFrom(filterFrom)
                .filterTo(filterTo)
                .sort(sort)
                .pageCursor(pageCursor)
                .pageLimit(pageLimit));
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling LogsApi#listLogsGet");
            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:

              
export DD_SITE="datadoghq.comus3.datadoghq.comdatadoghq.euddog-gov.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" java "Example.java"