---
title: Modificar una métrica basada en logs
description: Modifica una métrica basada en logs concreta de tu organización.
breadcrumbs: Documentación > API > Modificar una métrica basada en logs
---

> For the complete documentation index, see [llms.txt](https://dnd37xeb23o8n.cloudfront.net/stefon.simmons/docs-astro-web-10435/llms.txt).

# Modificar una métrica basada en logs

## v2 (latest)

| Datadog site      | API endpoint                                                               |
| ----------------- | -------------------------------------------------------------------------- |
| app.datadoghq.com | PATCH https://api.datadoghq.com/api/v2/logs/config/metrics/{metric_id}     |
| us3.datadoghq.com | PATCH https://api.us3.datadoghq.com/api/v2/logs/config/metrics/{metric_id} |
| us5.datadoghq.com | PATCH https://api.us5.datadoghq.com/api/v2/logs/config/metrics/{metric_id} |
| app.datadoghq.eu  | PATCH https://api.datadoghq.eu/api/v2/logs/config/metrics/{metric_id}      |
| ap1.datadoghq.com | PATCH https://api.ap1.datadoghq.com/api/v2/logs/config/metrics/{metric_id} |
| ap2.datadoghq.com | PATCH https://api.ap2.datadoghq.com/api/v2/logs/config/metrics/{metric_id} |
| uk1.datadoghq.com | PATCH https://api.uk1.datadoghq.com/api/v2/logs/config/metrics/{metric_id} |
| app.ddog-gov.com  | PATCH https://api.ddog-gov.com/api/v2/logs/config/metrics/{metric_id}      |
| us2.ddog-gov.com  | PATCH https://api.us2.ddog-gov.com/api/v2/logs/config/metrics/{metric_id}  |

### Overview

Modifica una métrica basada en logs concreta de tu organización.
Devuelve el objeto de métrica basada en logs del cuerpo de la solicitud cuando dicha solicitud es satisfactoria.

This endpoint requires the `logs_generate_metrics` permission.

### Arguments

#### Path Parameters

| Field                  | Type   | Description                       |
| ---------------------- | ------ | --------------------------------- |
| metric_id [*required*] | string | The name of the log-based metric. |

### Request

#### Body Data (required)

Nueva definición de la métrica basada en logs.

{% tabs %}
{% tab label="Model" %}
| Parent field | Field                   | Type     | Description                                                                                                                                |
| ------------ | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|              | data [*required*]       | object   | Cuerpo de la nueva métrica basada en logs.                                                                                                 |
| data         | attributes [*required*] | object   | The log-based metric properties that will be updated.                                                                                      |
| attributes   | compute                 | object   | The compute rule to compute the log-based metric.                                                                                          |
| compute      | include_percentiles     | boolean  | Toggle to include or exclude percentile aggregations for distribution metrics. Only present when the `aggregation_type` is `distribution`. |
| attributes   | filter                  | object   | The log-based metric filter. Logs matching this filter will be aggregated in this metric.                                                  |
| filter       | query                   | string   | The search query - following the log search syntax. Default: `*`.                                                                          |
| attributes   | group_by                | [object] | The rules for the group by.                                                                                                                |
| group_by     | path [*required*]       | string   | The path to the value the log-based metric will be aggregated over.                                                                        |
| group_by     | tag_name                | string   | Eventual name of the tag that gets created. By default, the path attribute is used as the tag name.                                        |
| data         | type [*required*]       | enum     | The type of the resource. The value should always be logs_metrics. Allowed enum values: `logs_metrics`. Default: `logs_metrics`.           |
{% /tab %}

{% tab label="Example" %}
**Update a log-based metric returns "OK" response**

```json
{
  "data": {
    "type": "logs_metrics",
    "attributes": {
      "filter": {
        "query": "service:web* AND @http.status_code:[200 TO 299]-updated"
      }
    }
  }
}
```

**Update a log-based metric with include\_percentiles field returns "OK" response**

```json
{
  "data": {
    "type": "logs_metrics",
    "attributes": {
      "compute": {
        "include_percentiles": false
      }
    }
  }
}
```
{% /tab %}
{% /tabs %}

### Response

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

{% tabs %}
{% tab label="Model" %}
The log-based metric object.

| Parent field | Field               | Type     | Description                                                                                                                                |
| ------------ | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|              | data                | object   | The log-based metric properties.                                                                                                           |
| data         | attributes          | object   | The object describing a Datadog log-based metric.                                                                                          |
| attributes   | compute             | object   | The compute rule to compute the log-based metric.                                                                                          |
| compute      | aggregation_type    | enum     | The type of aggregation to use. Allowed enum values: `count`, `distribution`.                                                              |
| compute      | include_percentiles | boolean  | Toggle to include or exclude percentile aggregations for distribution metrics. Only present when the `aggregation_type` is `distribution`. |
| compute      | path                | string   | The path to the value the log-based metric will aggregate on (only used if the aggregation type is a "distribution").                      |
| attributes   | filter              | object   | The log-based metric filter. Logs matching this filter will be aggregated in this metric.                                                  |
| filter       | query               | string   | The search query - following the log search syntax.                                                                                        |
| attributes   | group_by            | [object] | The rules for the group by.                                                                                                                |
| group_by     | path                | string   | The path to the value the log-based metric will be aggregated over.                                                                        |
| group_by     | tag_name            | string   | Eventual name of the tag that gets created. By default, the path attribute is used as the tag name.                                        |
| data         | id                  | string   | The name of the log-based metric.                                                                                                          |
| data         | type                | enum     | The type of the resource. The value should always be logs_metrics. Allowed enum values: `logs_metrics`. Default: `logs_metrics`.           |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "attributes": {
      "compute": {
        "aggregation_type": "distribution",
        "include_percentiles": true,
        "path": "@duration"
      },
      "filter": {
        "query": "service:web-api AND @http.status_code:[200 TO 299]"
      },
      "group_by": [
        {
          "path": "@http.status_code",
          "tag_name": "status_code"
        }
      ]
    },
    "id": "logs.page.load.count",
    "type": "logs_metrics"
  }
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

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

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

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

{% tab label="403" %}
Not Authorized

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

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

{% tab label="404" %}
Not Found

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

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

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

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

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

### Code Example

{% tabs %}
{% tab label="Curl" %}
```bash
# Path parameters
export metric_id="CHANGE_ME"

# 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 PATCH "https://api.${DD_SITE}/api/v2/logs/config/metrics/${metric_id}" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "data": {
    "type": "logs_metrics",
    "attributes": {
      "filter": {
        "query": "service:web* AND @http.status_code:[200 TO 299]-updated"
      }
    }
  }
}
EOF
```

```bash
# Path parameters
export metric_id="CHANGE_ME"

# 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 PATCH "https://api.${DD_SITE}/api/v2/logs/config/metrics/${metric_id}" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "data": {
    "type": "logs_metrics",
    "attributes": {
      "compute": {
        "include_percentiles": false
      }
    }
  }
}
EOF
```
{% /tab %}

{% tab label="Go" %}
```go
// Update a log-based metric returns "OK" response

package main

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

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

func main() {
	// there is a valid "logs_metric" in the system
	LogsMetricDataID := os.Getenv("LOGS_METRIC_DATA_ID")

	body := datadogV2.LogsMetricUpdateRequest{
		Data: datadogV2.LogsMetricUpdateData{
			Type: datadogV2.LOGSMETRICTYPE_LOGS_METRICS,
			Attributes: datadogV2.LogsMetricUpdateAttributes{
				Filter: &datadogV2.LogsMetricFilter{
					Query: datadog.PtrString("service:web* AND @http.status_code:[200 TO 299]-updated"),
				},
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewLogsMetricsApi(apiClient)
	resp, r, err := api.UpdateLogsMetric(ctx, LogsMetricDataID, body)

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

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

```go
// Update a log-based metric with include_percentiles field returns "OK" response

package main

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

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

func main() {
	// there is a valid "logs_metric_percentile" in the system
	LogsMetricPercentileDataID := os.Getenv("LOGS_METRIC_PERCENTILE_DATA_ID")

	body := datadogV2.LogsMetricUpdateRequest{
		Data: datadogV2.LogsMetricUpdateData{
			Type: datadogV2.LOGSMETRICTYPE_LOGS_METRICS,
			Attributes: datadogV2.LogsMetricUpdateAttributes{
				Compute: &datadogV2.LogsMetricUpdateCompute{
					IncludePercentiles: datadog.PtrBool(false),
				},
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewLogsMetricsApi(apiClient)
	resp, r, err := api.UpdateLogsMetric(ctx, LogsMetricPercentileDataID, body)

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

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `LogsMetricsApi.UpdateLogsMetric`:\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
// Update a log-based metric returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.LogsMetricsApi;
import com.datadog.api.client.v2.model.LogsMetricFilter;
import com.datadog.api.client.v2.model.LogsMetricResponse;
import com.datadog.api.client.v2.model.LogsMetricType;
import com.datadog.api.client.v2.model.LogsMetricUpdateAttributes;
import com.datadog.api.client.v2.model.LogsMetricUpdateData;
import com.datadog.api.client.v2.model.LogsMetricUpdateRequest;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    LogsMetricsApi apiInstance = new LogsMetricsApi(defaultClient);

    // there is a valid "logs_metric" in the system
    String LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY =
        System.getenv("LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY");
    String LOGS_METRIC_DATA_ID = System.getenv("LOGS_METRIC_DATA_ID");

    LogsMetricUpdateRequest body =
        new LogsMetricUpdateRequest()
            .data(
                new LogsMetricUpdateData()
                    .type(LogsMetricType.LOGS_METRICS)
                    .attributes(
                        new LogsMetricUpdateAttributes()
                            .filter(
                                new LogsMetricFilter()
                                    .query(
                                        "service:web* AND @http.status_code:[200 TO"
                                            + " 299]-updated"))));

    try {
      LogsMetricResponse result = apiInstance.updateLogsMetric(LOGS_METRIC_DATA_ID, body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling LogsMetricsApi#updateLogsMetric");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
```

```java
// Update a log-based metric with include_percentiles field returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.LogsMetricsApi;
import com.datadog.api.client.v2.model.LogsMetricResponse;
import com.datadog.api.client.v2.model.LogsMetricType;
import com.datadog.api.client.v2.model.LogsMetricUpdateAttributes;
import com.datadog.api.client.v2.model.LogsMetricUpdateCompute;
import com.datadog.api.client.v2.model.LogsMetricUpdateData;
import com.datadog.api.client.v2.model.LogsMetricUpdateRequest;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    LogsMetricsApi apiInstance = new LogsMetricsApi(defaultClient);

    // there is a valid "logs_metric_percentile" in the system
    String LOGS_METRIC_PERCENTILE_DATA_ID = System.getenv("LOGS_METRIC_PERCENTILE_DATA_ID");

    LogsMetricUpdateRequest body =
        new LogsMetricUpdateRequest()
            .data(
                new LogsMetricUpdateData()
                    .type(LogsMetricType.LOGS_METRICS)
                    .attributes(
                        new LogsMetricUpdateAttributes()
                            .compute(new LogsMetricUpdateCompute().includePercentiles(false))));

    try {
      LogsMetricResponse result =
          apiInstance.updateLogsMetric(LOGS_METRIC_PERCENTILE_DATA_ID, body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling LogsMetricsApi#updateLogsMetric");
      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
"""
Update a log-based metric returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.logs_metrics_api import LogsMetricsApi
from datadog_api_client.v2.model.logs_metric_filter import LogsMetricFilter
from datadog_api_client.v2.model.logs_metric_type import LogsMetricType
from datadog_api_client.v2.model.logs_metric_update_attributes import LogsMetricUpdateAttributes
from datadog_api_client.v2.model.logs_metric_update_data import LogsMetricUpdateData
from datadog_api_client.v2.model.logs_metric_update_request import LogsMetricUpdateRequest

# there is a valid "logs_metric" in the system
LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY = environ["LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY"]
LOGS_METRIC_DATA_ID = environ["LOGS_METRIC_DATA_ID"]

body = LogsMetricUpdateRequest(
    data=LogsMetricUpdateData(
        type=LogsMetricType.LOGS_METRICS,
        attributes=LogsMetricUpdateAttributes(
            filter=LogsMetricFilter(
                query="service:web* AND @http.status_code:[200 TO 299]-updated",
            ),
        ),
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = LogsMetricsApi(api_client)
    response = api_instance.update_logs_metric(metric_id=LOGS_METRIC_DATA_ID, body=body)

    print(response)
```

```python
"""
Update a log-based metric with include_percentiles field returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.logs_metrics_api import LogsMetricsApi
from datadog_api_client.v2.model.logs_metric_type import LogsMetricType
from datadog_api_client.v2.model.logs_metric_update_attributes import LogsMetricUpdateAttributes
from datadog_api_client.v2.model.logs_metric_update_compute import LogsMetricUpdateCompute
from datadog_api_client.v2.model.logs_metric_update_data import LogsMetricUpdateData
from datadog_api_client.v2.model.logs_metric_update_request import LogsMetricUpdateRequest

# there is a valid "logs_metric_percentile" in the system
LOGS_METRIC_PERCENTILE_DATA_ID = environ["LOGS_METRIC_PERCENTILE_DATA_ID"]

body = LogsMetricUpdateRequest(
    data=LogsMetricUpdateData(
        type=LogsMetricType.LOGS_METRICS,
        attributes=LogsMetricUpdateAttributes(
            compute=LogsMetricUpdateCompute(
                include_percentiles=False,
            ),
        ),
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = LogsMetricsApi(api_client)
    response = api_instance.update_logs_metric(metric_id=LOGS_METRIC_PERCENTILE_DATA_ID, 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
# Update a log-based metric returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::LogsMetricsAPI.new

# there is a valid "logs_metric" in the system
LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY = ENV["LOGS_METRIC_DATA_ATTRIBUTES_FILTER_QUERY"]
LOGS_METRIC_DATA_ID = ENV["LOGS_METRIC_DATA_ID"]

body = DatadogAPIClient::V2::LogsMetricUpdateRequest.new({
  data: DatadogAPIClient::V2::LogsMetricUpdateData.new({
    type: DatadogAPIClient::V2::LogsMetricType::LOGS_METRICS,
    attributes: DatadogAPIClient::V2::LogsMetricUpdateAttributes.new({
      filter: DatadogAPIClient::V2::LogsMetricFilter.new({
        query: "service:web* AND @http.status_code:[200 TO 299]-updated",
      }),
    }),
  }),
})
p api_instance.update_logs_metric(LOGS_METRIC_DATA_ID, body)
```

```ruby
# Update a log-based metric with include_percentiles field returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::LogsMetricsAPI.new

# there is a valid "logs_metric_percentile" in the system
LOGS_METRIC_PERCENTILE_DATA_ID = ENV["LOGS_METRIC_PERCENTILE_DATA_ID"]

body = DatadogAPIClient::V2::LogsMetricUpdateRequest.new({
  data: DatadogAPIClient::V2::LogsMetricUpdateData.new({
    type: DatadogAPIClient::V2::LogsMetricType::LOGS_METRICS,
    attributes: DatadogAPIClient::V2::LogsMetricUpdateAttributes.new({
      compute: DatadogAPIClient::V2::LogsMetricUpdateCompute.new({
        include_percentiles: false,
      }),
    }),
  }),
})
p api_instance.update_logs_metric(LOGS_METRIC_PERCENTILE_DATA_ID, 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
// Update a log-based metric returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_logs_metrics::LogsMetricsAPI;
use datadog_api_client::datadogV2::model::LogsMetricFilter;
use datadog_api_client::datadogV2::model::LogsMetricType;
use datadog_api_client::datadogV2::model::LogsMetricUpdateAttributes;
use datadog_api_client::datadogV2::model::LogsMetricUpdateData;
use datadog_api_client::datadogV2::model::LogsMetricUpdateRequest;

#[tokio::main]
async fn main() {
    // there is a valid "logs_metric" in the system
    let logs_metric_data_id = std::env::var("LOGS_METRIC_DATA_ID").unwrap();
    let body = LogsMetricUpdateRequest::new(LogsMetricUpdateData::new(
        LogsMetricUpdateAttributes::new().filter(
            LogsMetricFilter::new()
                .query("service:web* AND @http.status_code:[200 TO 299]-updated".to_string()),
        ),
        LogsMetricType::LOGS_METRICS,
    ));
    let configuration = datadog::Configuration::new();
    let api = LogsMetricsAPI::with_config(configuration);
    let resp = api
        .update_logs_metric(logs_metric_data_id.clone(), body)
        .await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
```

```rust
// Update a log-based metric with include_percentiles field returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_logs_metrics::LogsMetricsAPI;
use datadog_api_client::datadogV2::model::LogsMetricType;
use datadog_api_client::datadogV2::model::LogsMetricUpdateAttributes;
use datadog_api_client::datadogV2::model::LogsMetricUpdateCompute;
use datadog_api_client::datadogV2::model::LogsMetricUpdateData;
use datadog_api_client::datadogV2::model::LogsMetricUpdateRequest;

#[tokio::main]
async fn main() {
    // there is a valid "logs_metric_percentile" in the system
    let logs_metric_percentile_data_id = std::env::var("LOGS_METRIC_PERCENTILE_DATA_ID").unwrap();
    let body = LogsMetricUpdateRequest::new(LogsMetricUpdateData::new(
        LogsMetricUpdateAttributes::new()
            .compute(LogsMetricUpdateCompute::new().include_percentiles(false)),
        LogsMetricType::LOGS_METRICS,
    ));
    let configuration = datadog::Configuration::new();
    let api = LogsMetricsAPI::with_config(configuration);
    let resp = api
        .update_logs_metric(logs_metric_percentile_data_id.clone(), 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="<API-KEY>" DD_APP_KEY="<APP-KEY>" cargo run
```
{% /tab %}

{% tab label="TypeScript" %}
```typescript
/**
 * Update a log-based metric returns "OK" response
 */

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

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.LogsMetricsApi(configuration);

// there is a valid "logs_metric" in the system
const LOGS_METRIC_DATA_ID = process.env.LOGS_METRIC_DATA_ID as string;

const params: v2.LogsMetricsApiUpdateLogsMetricRequest = {
  body: {
    data: {
      type: "logs_metrics",
      attributes: {
        filter: {
          query: "service:web* AND @http.status_code:[200 TO 299]-updated",
        },
      },
    },
  },
  metricId: LOGS_METRIC_DATA_ID,
};

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

```typescript
/**
 * Update a log-based metric with include_percentiles field returns "OK" response
 */

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

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.LogsMetricsApi(configuration);

// there is a valid "logs_metric_percentile" in the system
const LOGS_METRIC_PERCENTILE_DATA_ID = process.env
  .LOGS_METRIC_PERCENTILE_DATA_ID as string;

const params: v2.LogsMetricsApiUpdateLogsMetricRequest = {
  body: {
    data: {
      type: "logs_metrics",
      attributes: {
        compute: {
          includePercentiles: false,
        },
      },
    },
  },
  metricId: LOGS_METRIC_PERCENTILE_DATA_ID,
};

apiInstance
  .updateLogsMetric(params)
  .then((data: v2.LogsMetricResponse) => {
    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 %}
