---
title: ログを検索する
description: リストエンドポイントは、ログ検索クエリに一致するログを返します。 [結果はページ分割されます][1]。
breadcrumbs: ドキュメント > API > ログを検索する
---

> For the complete documentation index, see [llms.txt](https://dnd37xeb23o8n.cloudfront.net/jen.gilbert/astro-base/llms.txt).

# ログを検索する

## v1 (latest)

| Datadog site      | API endpoint                                                |
| ----------------- | ----------------------------------------------------------- |
| 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 |
| app.datadoghq.eu  | POST https://api.datadoghq.eu/api/v1/logs-queries/list      |
| 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 |
| uk1.datadoghq.com | POST https://api.uk1.datadoghq.com/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  |

### Overview

リストエンドポイントは、ログ検索クエリに一致するログを返します。
[結果はページ分割されます](https://dnd37xeb23o8n.cloudfront.net/logs/guide/collect-multiple-logs-with-pagination.md)。

**組織のログのアーカイブを検討されている場合は、
リスト API の代わりに Datadog のアーカイブ機能の使用を検討します。
[Datadog ログアーカイブのドキュメント](https://docs.datadoghq.com/logs/archives.md) を参照してください。**

**注**: このエンドポイントは、ログを利用するお客様に対してデフォルトで有効になっています。無効にするには、[Datadog サポート](https://docs.datadoghq.com/help.md) までお問い合わせください。

This endpoint requires the `logs_read_data` permission.

### Request

#### Body Data (required)

ログフィルター

{% tabs %}
{% tab label="Model" %}
| Parent field | Field             | Type      | Description                                                                                                                                                                                                                                                  |
| ------------ | ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|              | index             | string    | 組織からログのリストを取得するためにリクエストとともに送信するオブジェクト。                                                                                                                                                                                                                       |
|              | 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 label="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 %}
{% /tabs %}

### Response

{% tabs %}
{% tab label="200" %}
OK

{% tabs %}
{% tab label="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.                                                                                                                                                                                                                  |
|              | requestId  | string    | Unique identifier of the request.                                                                                                                                                                                                                                                                                          |
|              | status     | string    | Status of the response.                                                                                                                                                                                                                                                                                                    |
{% /tab %}

{% tab label="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",
  "requestId": "example-request-id",
  "status": "string"
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="400" %}
Bad Request

{% tabs %}
{% tab label="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 label="Example" %}
```json
{
  "error": {
    "code": "string",
    "details": [],
    "message": "string"
  }
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="403" %}
Authentication error

{% tabs %}
{% tab label="Model" %}
Error response object.

| Field               | Type     | Description                          |
| ------------------- | -------- | ------------------------------------ |
| errors [*required*] | [string] | Array of errors returned by the API. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="429" %}
Too many requests

{% tabs %}
{% tab label="Model" %}
Error response object.

| Field               | Type     | Description                          |
| ------------------- | -------- | ------------------------------------ |
| errors [*required*] | [string] | Array of errors returned by the API. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}
{% /tabs %}

### Code Example

{% tabs %}
{% tab label="Curl" %}
```bash
# Set your Datadog site and credentials
export DD_SITE="datadoghq.com" # Or us3.datadoghq.com, us5.datadoghq.com, datadoghq.eu, ap1.datadoghq.com, ap2.datadoghq.com, uk1.datadoghq.com, ddog-gov.com, us2.ddog-gov.com
# Use a Personal Access Token or Service Access Token
export DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>"

curl -X POST "https://api.${DD_SITE}/api/v1/logs-queries/list" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "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"
  }
}
EOF
```
{% /tab %}

{% tab label="Go" %}
```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())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=go) and then save the example to `main.go` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" go run "main.go"
```
{% /tab %}

{% tab label="Java" %}
```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();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=java) and then save the example to `Example.java` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" java "Example.java"
```
{% /tab %}

{% tab label="Python" %}
```python
"""
Search test logs returns "OK" response
"""

from datetime import datetime
from dateutil.relativedelta import relativedelta
from os import environ
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()
configuration.access_token = environ["DD_BEARER_TOKEN"]
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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=python) and then save the example to `example.py` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" python3 "example.py"
```
{% /tab %}

{% tab label="Ruby" %}
```ruby
# Search test logs returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=ruby) and then save the example to `example.rb` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" rb "example.rb"
```
{% /tab %}

{% tab label="Rust" %}
```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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=rust) and then save the example to `src/main.rs` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
```
{% /tab %}

{% tab label="TypeScript" %}
```typescript
/**
 * Search test logs returns "OK" response
 */

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

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
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://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=typescript) and then save the example to `example.ts` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" tsc "example.ts"
```
{% /tab %}
{% /tabs %}
