---
title: Search logs
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: Docs > API Reference > Logs
---

# Search logs{% #search-logs %}
Copy pageCopied
{% tab title="v1" %}

| Datadog site      | API endpoint                                                |
| ----------------- | ----------------------------------------------------------- |
| ap1.datadoghq.com | POST https://api.ap1.datadoghq.com/api/v1/logs-queries/list |
| ap2.datadoghq.com | POST https://api.ap2.datadoghq.com/api/v1/logs-queries/list |
| app.datadoghq.eu  | POST https://api.datadoghq.eu/api/v1/logs-queries/list      |
| app.ddog-gov.com  | POST https://api.ddog-gov.com/api/v1/logs-queries/list      |
| us2.ddog-gov.com  | POST https://api.us2.ddog-gov.com/api/v1/logs-queries/list  |
| app.datadoghq.com | POST https://api.datadoghq.com/api/v1/logs-queries/list     |
| us3.datadoghq.com | POST https://api.us3.datadoghq.com/api/v1/logs-queries/list |
| us5.datadoghq.com | POST https://api.us5.datadoghq.com/api/v1/logs-queries/list |

### Overview



List endpoint returns logs that match a log search query. [Results are paginated](https://docs.datadoghq.com/logs/guide/collect-multiple-logs-with-pagination.md).

**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](https://docs.datadoghq.com/logs/archives.md).**

**Note**: This endpoint is enabled by default for logs customers. To disable it, contact [Datadog support](https://docs.datadoghq.com/help/).
This endpoint requires the `logs_read_data` permission.


### Request

#### Body Data (required)

Logs filter

{% tab title="Model" %}

| Parent field | Field                  | 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 `desc` results. 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.                                                                                                                                       |
| time         | from [*required*] | date-time | Minimum timestamp for requested logs.                                                                                                                                     |
| time         | timezone               | string    | Timezone can be specified both as an offset (for example "UTC+03:00") or a regional zone (for example "Europe/Paris").                                                    |
| time         | to [*required*]   | date-time | Maximum timestamp for requested logs.                                                                                                                                     |

{% /tab %}

{% tab title="Example" %}

```json
{
  "index": "main",
  "query": "host:Test*",
  "sort": "asc",
  "time": {
    "from": "2021-11-11T10:11:11+00:00",
    "timezone": "Europe/Paris",
    "to": "2021-11-11T11:11:11+00:00"
  }
}
```

{% /tab %}

### Response

{% tab title="200" %}
OK
{% tab title="Model" %}
Response object with all logs matching the request and pagination information.

| Parent field | Field      | Type      | Description                                                                                                                                                                                                                                                                                                                |
| ------------ | ---------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|              | logs       | [object]  | Array of logs matching the request and the `nextLogId` if sent.                                                                                                                                                                                                                                                            |
| logs         | content    | object    | JSON object containing all log attributes and their associated values.                                                                                                                                                                                                                                                     |
| content      | attributes | object    | JSON object of attributes from your log.                                                                                                                                                                                                                                                                                   |
| content      | host       | string    | Name of the machine from where the logs are being sent.                                                                                                                                                                                                                                                                    |
| content      | message    | string    | The message [reserved attribute](https://docs.datadoghq.com/logs/log_collection.md#reserved-attributes) 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. |
| content      | 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.                                                                                                                                                |
| content      | tags       | [string]  | Array of tags associated with your log.                                                                                                                                                                                                                                                                                    |
| content      | timestamp  | date-time | Timestamp of your log.                                                                                                                                                                                                                                                                                                     |
| logs         | id         | string    | 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.                                                                                                                                                                                                                                                                                                    |

{% /tab %}

{% tab title="Example" %}

```json
{
  "logs": [
    {
      "content": {
        "attributes": {
          "customAttribute": 123,
          "duration": 2345
        },
        "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"
}
```

{% /tab %}

{% /tab %}

{% tab title="400" %}
Bad Request
{% tab title="Model" %}
Response returned by the Logs API when errors occur.

| Parent field | Field   | Type     | Description                    |
| ------------ | ------- | -------- | ------------------------------ |
|              | error   | object   | Error returned by the Logs API |
| error        | code    | string   | Code identifying the error     |
| error        | details | [object] | Additional error details       |
| error        | message | string   | Error message                  |

{% /tab %}

{% tab title="Example" %}

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

{% /tab %}

{% /tab %}

{% tab title="403" %}
Authentication error
{% tab title="Model" %}
Error response object.

| Field                    | Type     | Description                          |
| ------------------------ | -------- | ------------------------------------ |
| errors [*required*] | [string] | Array of errors returned by the API. |

{% /tab %}

{% tab title="Example" %}

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

{% /tab %}

{% /tab %}

{% tab title="429" %}
Too many requests
{% tab title="Model" %}
Error response object.

| Field                    | Type     | Description                          |
| ------------------------ | -------- | ------------------------------------ |
| errors [*required*] | [string] | Array of errors returned by the API. |

{% /tab %}

{% tab title="Example" %}

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

{% /tab %}

{% /tab %}

### Code Example

##### 
                          \## default
# 
 \# Curl command curl -X POST "https://api.datadoghq.com/api/v1/logs-queries/list" \
-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
{
  "index": "retention-3,retention-15",
  "limit": 25,
  "query": "service:web* AND @http.status_code:[200 TO 299]",
  "sort": "desc",
  "time": {
    "from": "2020-02-02T02:02:02.202Z",
    "to": "2020-02-20T02:02:02.202Z"
  }
}
EOF 
                        
##### 

```go
// Search test logs returns "OK" response

package main

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

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

func main() {
	body := datadogV1.LogsListRequest{
		Index: datadog.PtrString("main"),
		Query: datadog.PtrString("host:Test*"),
		Sort:  datadogV1.LOGSSORT_TIME_ASCENDING.Ptr(),
		Time: datadogV1.LogsListRequestTime{
			From:     time.Now().Add(time.Hour * -1),
			Timezone: datadog.PtrString("Europe/Paris"),
			To:       time.Now(),
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV1.NewLogsApi(apiClient)
	resp, r, err := api.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)
	}

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

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=go) and then save the example to `main.go` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
##### 

```java
// Search test logs returns "OK" response
import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v1.api.LogsApi;
import com.datadog.api.client.v1.model.LogsListRequest;
import com.datadog.api.client.v1.model.LogsListRequestTime;
import com.datadog.api.client.v1.model.LogsListResponse;
import com.datadog.api.client.v1.model.LogsSort;
import java.time.OffsetDateTime;

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

    LogsListRequest body =
        new LogsListRequest()
            .index("main")
            .query("host:Test*")
            .sort(LogsSort.TIME_ASCENDING)
            .time(
                new LogsListRequestTime()
                    .from(OffsetDateTime.now().plusHours(-1))
                    .timezone("Europe/Paris")
                    .to(OffsetDateTime.now()));

    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](https://docs.datadoghq.com/api/latest.md?code-lang=java) and then save the example to `Example.java` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
##### 

```python
"""
Search test logs returns "OK" response
"""

from datetime import datetime
from dateutil.relativedelta import relativedelta
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v1.api.logs_api import LogsApi
from datadog_api_client.v1.model.logs_list_request import LogsListRequest
from datadog_api_client.v1.model.logs_list_request_time import LogsListRequestTime
from datadog_api_client.v1.model.logs_sort import LogsSort

body = LogsListRequest(
    index="main",
    query="host:Test*",
    sort=LogsSort.TIME_ASCENDING,
    time=LogsListRequestTime(
        _from=(datetime.now() + relativedelta(hours=-1)),
        timezone="Europe/Paris",
        to=datetime.now(),
    ),
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = LogsApi(api_client)
    response = api_instance.list_logs(body=body)

    print(response)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=python) and then save the example to `example.py` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
##### 

```ruby
# Search test logs returns "OK" response

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

body = DatadogAPIClient::V1::LogsListRequest.new({
  index: "main",
  query: "host:Test*",
  sort: DatadogAPIClient::V1::LogsSort::TIME_ASCENDING,
  time: DatadogAPIClient::V1::LogsListRequestTime.new({
    from: (Time.now + -1 * 3600),
    timezone: "Europe/Paris",
    to: Time.now,
  }),
})
p api_instance.list_logs(body)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=ruby) and then save the example to `example.rb` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
##### 

```rust
// Search test logs returns "OK" response
use chrono::{DateTime, Utc};
use datadog_api_client::datadog;
use datadog_api_client::datadogV1::api_logs::LogsAPI;
use datadog_api_client::datadogV1::model::LogsListRequest;
use datadog_api_client::datadogV1::model::LogsListRequestTime;
use datadog_api_client::datadogV1::model::LogsSort;

#[tokio::main]
async fn main() {
    let body = LogsListRequest::new(
        LogsListRequestTime::new(
            DateTime::parse_from_rfc3339("2021-11-11T10:11:11+00:00")
                .expect("Failed to parse datetime")
                .with_timezone(&Utc),
            DateTime::parse_from_rfc3339("2021-11-11T11:11:11+00:00")
                .expect("Failed to parse datetime")
                .with_timezone(&Utc),
        )
        .timezone("Europe/Paris".to_string()),
    )
    .index("main".to_string())
    .query("host:Test*".to_string())
    .sort(LogsSort::TIME_ASCENDING);
    let configuration = datadog::Configuration::new();
    let api = LogsAPI::with_config(configuration);
    let resp = api.list_logs(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=rust) and then save the example to `src/main.rs` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
##### 

```typescript
/**
 * Search test logs returns "OK" response
 */

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

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

const params: v1.LogsApiListLogsRequest = {
  body: {
    index: "main",
    query: "host:Test*",
    sort: "asc",
    time: {
      from: new Date(new Date().getTime() + -1 * 3600 * 1000),
      timezone: "Europe/Paris",
      to: new Date(),
    },
  },
};

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

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=typescript) and then save the example to `example.ts` and run following commands:
    DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"
{% /tab %}
