
# 统计top n的日志组或日志流流量 - ListTopnTrafficStatistics
#### 功能介绍
统计top n的日志组或日志流流量。按流量大小排名前N的日志组或日志流，支持自定义时间、流量类型等方式进行流量统计，统计结果用于资源监控、异常流量定位分析等，帮助您进行实时流量统计和数据回溯。
#### 调用方法
请参见[如何调用API](https://support.huaweicloud.com/api-lts/lts_api_0003.html)。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限。
- 如果使用角色与策略授权，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-lts/lts_api_0046.html)。
- 如果使用身份策略授权，需具备如下身份策略权限。
  
  | 授权项                      | 访问级别 | 资源类型（\*为必须） | 条件键 | 别名            | 依赖的授权项 |
  |:---|:---|:---|:---|:---|:---|
  | lts:trafficStatistic:get | Read | -           | -   | lts:logs:list | -      |
     
  
 
#### URI
POST /v2/{project_id}/lts/topn-traffic-statistics
表1路径参数 
| 参数         | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|:---|:---|:---|:---|
| project_id | 是    | String | **参数解释：** 项目ID，可以从调用API处获取，也可以从控制台获取。获取方式请参见：[获取项目ID](https://support.huaweicloud.com/api-lts/lts_api_0006.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
#### 请求参数
表2请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|:---|
| X-Auth-Token | 是    | String | **参数解释：** 从IAM服务获取的用户Token，获取方式请参见：[获取用户Token](https://support.huaweicloud.com/api-lts/lts_api_0004.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| Content-Type | 是    | String | **参数解释：** 用于定义消息体的格式，该字段填为：application/json;charset=utf8。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                  |
   
表3请求Body参数 
| 参数            | 是否必选 | 参数类型                 | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
|:---|:---|:---|:---|
| end_time      | 是    | Long                 | **参数解释：** 按照时间范围查询日志的结束时间，时间戳（秒级）。 参数start_time和end_time组成的时间区间，既包含起始时间也包含结束时间。 **约束限制：** - 查询时间区间最大为30天   - start_time和end_time取值不能相同。    **取值范围：** 毫秒级时间戳，表示从1970-1-1 00:00:00 UTC开始计算的毫秒数。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| is_desc       | 是    | Boolean              | **参数解释：** 是否对流量进行排序。 **约束限制：** 不涉及。 **取值范围：** - true：降序。   - fase：升序。    **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| resource_type | 是    | String               | **参数解释：** 资源ID。不同的资源类型（resource_type），资源ID不同。 - 当资源类型为log_group时 ，resource_id是日志组ID。   - 当资源类型为log_stream时，resource_id是日志流ID。   - 当资源类型为tenant时， resource_id 为空。    **约束限制：** 不涉及。 **取值范围：** 不涉及 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| sort_by       | 是    | String               | **参数解释：** 根据流量类型进行排序，该参数取值为index、wite、storage、basicTransfer、seniorTransfer、或coldStorage中任意一个。 **约束限制：** 不涉及 **取值范围：** - index：索引   - write：读写   - storage：存储   - basicTransfer：基础转储   - seniorTransfer：高级转储   - coldStorage：冷存储量    **默认取值：** 不涉及。 |
| start_time    | 是    | Long                 | **参数解释：** 按照时间范围查询日志的结束时间，时间戳（秒级）。 参数start_time和end_time组成的时间区间，既包含起始时间也包含结束时间。 **约束限制：** - 查询时间区间最大为30天   - start_time和end_time取值不能相同。    **取值范围：** 毫秒级时间戳，表示从1970-1-1 00:00:00 UTC开始计算的毫秒数。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| topn          | 是    | Integer              | **参数解释：** 查询前多少条流量，n表示流量条数。 **约束限制：** 不涉及 **取值范围：** 1\~100 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| filter        | 是    | Map\<String,String\> | **参数解释：** 统计流量的过滤条件，格式为key/value键值对。根据日志组ID和日志流ID进行过滤。 - key：log_group_id或log_stream_id   - value：填写具体的log_group_id或log_stream_id。    例如： *{ "log_group_id": "xxxxxx" }* **约束限制：** 不涉及                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| search_list   | 是    | Array of strings     | **参数解释：** 查询流量列表，字符串数组可多种搭配，只能在index/write/storage/basicTransfer/seniorTransfer/coldStorage中选填。 例如： *"search_list": \[ "index", "write", "storage" \]* **约束限制：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
   
#### 响应参数
**状态码：200**
表4响应Body参数 
| 参数      | 参数类型                                                                                     | 描述                                                                          |
|:---|:---|:---|
| results | Array of [ResultsTopnBody] objects | **参数解释：** 统计top n的日志组或日志流流量结果。 |
   
 表5ResultsTopnBody 
| 参数                    | 参数类型    | 描述                                                                                                                                                                                                       |
|:---|:---|:---|
| index_traffic         | Double  | **参数解释：** 索引流量（byte），流量类型为index时，返回的流量。 **取值范围：** 不涉及。            |
| storage               | Double  | **参数解释：** 存储流量（byte），流量类型为storag时，返回的流量。 **取值范围：** 不涉及。           |
| write_traffic         | Double  | **参数解释：** 读写流量（byte），流量类型为write时，返回的流量。 **取值范围：** 不涉及。            |
| log_group_id          | String  | **参数解释：** 日志组ID。 **取值范围：** 不涉及。                                   |
| log_group_name        | String  | **参数解释：** 日志组名称。 **取值范围：** 不涉及。                                   |
| log_group_name_alias  | String  | **参数解释：** 日志组名称别名。 **取值范围：** 不涉及。                                 |
| log_stream_id         | String  | **参数解释：** 日志流ID。 **取值范围：** 不涉及。                                   |
| log_stream_name       | String  | **参数解释：** 创建的日志流名称。 **取值范围：** 不涉及。                                |
| log_stream_name_alias | String  | **参数解释：** 日志流名称别名。 **取值范围：** 不涉及。                                 |
| basic_transfer        | Double  | **参数解释：** 基础转储流量（byte），流量类型为basicTransfer 时，返回的流量。 **取值范围：** 不涉及。 |
| senior_transfer       | Double  | **参数解释：** 高级转储流量（byte），流量类型为seniorTransfer时，返回的流量。 **取值范围：** 不涉及。 |
| is_agency_transfer    | Boolean | **参数解释：** 是否委托转储。当流量类型为基础转储或高级转储时，返回该参数。 **取值范围：** 不涉及。           |
| cold_storage          | Double  | **参数解释：** 冷存储量流量（byte），流量类型为coldStorage时，返回的流量。 **取值范围：** 不涉及。    |
   
**状态码：400**
表6响应Body参数 
| 参数           | 参数类型   | 描述                                                                                                                                                                                                                                     |
|:---|:---|:---|
| errorCode    | String | **参数解释：** 错误码，请参见：[错误码](https://support.huaweicloud.com/api-lts/ErrorCode.html)。 **取值范围：** 不涉及。 |
| errorMessage | String | **参数解释：** 调用失败响应信息描述。 **取值范围：** 不涉及。                                                            |
   
**状态码：500**
表7响应Body参数 
| 参数           | 参数类型   | 描述                                                                                                                                                                                                                                     |
|:---|:---|:---|
| errorCode    | String | **参数解释：** 错误码，请参见：[错误码](https://support.huaweicloud.com/api-lts/ErrorCode.html)。 **取值范围：** 不涉及。 |
| errorMessage | String | **参数解释：** 调用失败响应信息描述。 **取值范围：** 不涉及。                                                            |
   
#### 请求示例
统计top n的日志组或日志流流量。
```
/v2/{project_id}/lts/topn-traffic-statistics
{
  "sort_by" : "storage",
  "is_desc" : true,
  "resource_type" : "log_stream",
  "filter" : { },
  "start_time" : 1668668183969,
  "end_time" : 1669272983969,
  "search_list" : [ "index", "write", "storage" ],
  "topn" : 100
}
```
#### 响应示例
**状态码：200**
查询资源成功。
```
{
  "results" : [ {
    "index_traffic" : 0,
    "log_stream_id" : "6fd93d47-7630-4284-a622-311d0082f6bb",
    "log_stream_name" : "cmdb-cce-cluster",
    "storage" : 59810657587,
    "write_traffic" : 0
  }, {
    "index_traffic" : 0,
    "log_stream_id" : "504ec3dd-ac28-4783-babb-22a49f36afe3",
    "log_stream_name" : "CMSkaifatest",
    "storage" : 20033606015,
    "write_traffic" : 0
  }, {
    "index_traffic" : 6825703991,
    "log_stream_id" : "a14dacb0-5a13-43a8-89a3-ea5424d95133",
    "log_stream_name" : "ELB",
    "storage" : 15659303771,
    "write_traffic" : 1.3651407982E9
  }, {
    "index_traffic" : 302172889,
    "log_stream_id" : "25fe7494-7395-438e-8340-647613673ffa",
    "log_stream_name" : "LTStest-916-statefulset",
    "storage" : 316552589,
    "write_traffic" : 6.04345778E7
  }, {
    "index_traffic" : 0,
    "log_stream_id" : "956586fc-b828-44be-8672-0a323962a8fa",
    "log_stream_name" : "mongodb_slow",
    "storage" : 0,
    "write_traffic" : 0
  } ]
}
```
**状态码：400**
非法请求，建议根据error_msg直接修改该请求。
```
{
  "errorCode" : "LTS.0208",
  "errorMessage" : "The log stream does not existed"
}
```
**状态码：500**
表明服务端能被请求访问到，但是服务内部出错。
```
{
  "errorCode" : "LTS.0203",
  "errorMessage" : "Internal Server Error"
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  统计top n的日志组或日志流流量。
  ```
  package com.huaweicloud.sdk.test;
  import com.huaweicloud.sdk.core.auth.ICredential;
  import com.huaweicloud.sdk.core.auth.BasicCredentials;
  import com.huaweicloud.sdk.core.exception.ConnectionException;
  import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
  import com.huaweicloud.sdk.core.exception.ServiceResponseException;
  import com.huaweicloud.sdk.lts.v2.region.LtsRegion;
  import com.huaweicloud.sdk.lts.v2.*;
  import com.huaweicloud.sdk.lts.v2.model.*;
  import java.util.List;
  import java.util.ArrayList;
  import java.util.Map;
  import java.util.HashMap;
  public class ListTopnTrafficStatisticsSolution {
      public static void main(String[] args) {
          // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
          // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
          String ak = System.getenv("CLOUD_SDK_AK");
          String sk = System.getenv("CLOUD_SDK_SK");
          String projectId = "{project_id}";
          ICredential auth = new BasicCredentials()
                  .withProjectId(projectId)
                  .withAk(ak)
                  .withSk(sk);
          LtsClient client = LtsClient.newBuilder()
                  .withCredential(auth)
                  .withRegion(LtsRegion.valueOf("<YOUR REGION>"))
                  .build();
          ListTopnTrafficStatisticsRequest request = new ListTopnTrafficStatisticsRequest();
          TopnRequstBody body = new TopnRequstBody();
          List<String> listbodySearchList = new ArrayList<>();
          listbodySearchList.add("index");
          listbodySearchList.add("write");
          listbodySearchList.add("storage");
          body.withSearchList(listbodySearchList);
          body.withTopn(100);
          body.withStartTime(1668668183969L);
          body.withSortBy("storage");
          body.withResourceType("log_stream");
          body.withIsDesc(true);
          body.withEndTime(1669272983969L);
          request.withBody(body);
          try {
              ListTopnTrafficStatisticsResponse response = client.listTopnTrafficStatistics(request);
              System.out.println(response.toString());
          } catch (ConnectionException e) {
              e.printStackTrace();
          } catch (RequestTimeoutException e) {
              e.printStackTrace();
          } catch (ServiceResponseException e) {
              e.printStackTrace();
              System.out.println(e.getHttpStatusCode());
              System.out.println(e.getRequestId());
              System.out.println(e.getErrorCode());
              System.out.println(e.getErrorMsg());
          }
      }
  }
  ```
- [Python]
  统计top n的日志组或日志流流量。
  ```
  # coding: utf-8
  import os
  from huaweicloudsdkcore.auth.credentials import BasicCredentials
  from huaweicloudsdklts.v2.region.lts_region import LtsRegion
  from huaweicloudsdkcore.exceptions import exceptions
  from huaweicloudsdklts.v2 import *
  if __name__ == "__main__":
      # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak = os.environ["CLOUD_SDK_AK"]
      sk = os.environ["CLOUD_SDK_SK"]
      projectId = "{project_id}"
      credentials = BasicCredentials(ak, sk, projectId)
      client = LtsClient.new_builder() \
          .with_credentials(credentials) \
          .with_region(LtsRegion.value_of("<YOUR REGION>")) \
          .build()
      try:
          request = ListTopnTrafficStatisticsRequest()
          listSearchListbody = [
              "index",
              "write",
              "storage"
          ]
          request.body = TopnRequstBody(
              search_list=listSearchListbody,
              topn=100,
              start_time=1668668183969,
              sort_by="storage",
              resource_type="log_stream",
              is_desc=True,
              end_time=1669272983969
          )
          response = client.list_topn_traffic_statistics(request)
          print(response)
      except exceptions.ClientRequestException as e:
          print(e.status_code)
          print(e.request_id)
          print(e.error_code)
          print(e.error_msg)
  ```
- [Go]
  统计top n的日志组或日志流流量。
  ```
  package main
  import (
  "fmt"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
      lts "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/model"
      region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/region"
  )
  func main() {
      // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak := os.Getenv("CLOUD_SDK_AK")
      sk := os.Getenv("CLOUD_SDK_SK")
      projectId := "{project_id}"
      auth, err := basic.NewCredentialsBuilder().
          WithAk(ak).
          WithSk(sk).
          WithProjectId(projectId).
          SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      hcClient, err := lts.LtsClientBuilder().
           WithRegion(region.ValueOf("<YOUR REGION>")).
           WithCredential(auth).
           SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      client := lts.NewLtsClient(hcClient)
      request := &model.ListTopnTrafficStatisticsRequest{}
  var listSearchListbody = []string{
          "index",
      "write",
      "storage",
      }
  request.Body = &model.TopnRequstBody{
  SearchList: listSearchListbody,
  Topn: int32(100),
  StartTime: int64(1668668183969),
  SortBy: "storage",
  ResourceType: "log_stream",
  IsDesc: true,
  EndTime: int64(1669272983969),
  }
  response, err := client.ListTopnTrafficStatistics(request)
  if err == nil {
          fmt.Printf("%+v\n", response)
      } else {
          fmt.Println(err)
      }
  }
  ```
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/LTS/sdk?api=ListTopnTrafficStatistics)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述                         |
|:---|:---|
| 200 | 查询资源成功。                    |
| 400 | 非法请求，建议根据error_msg直接修改该请求。 |
| 500 | 表明服务端能被请求访问到，但是服务内部出错。     |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-lts/ErrorCode.html)。
