使用日志引入 API 将数据发送到 Azure Monitor 的示例代码

本文提供使用 日志引入 API 的示例代码。 每个示例都需要在运行代码之前创建以下组件。 请参阅 教程:使用日志引入 API(资源管理器模板)将数据发送到 Azure Monitor,从而了解创建这些配置为支持其中每个示例的组件的完整演练。

  • Log Analytics 工作区中的自定义表
  • 用于将数据定向到目标表的数据收集规则(DCR)
  • 有权访问 DCR 的 Microsoft Entra 应用程序
  • 如果使用专用链接,则使用数据收集终结点 (DCE)。 否则,请使用 DCR 日志终结点。

示例代码

以下 PowerShell 代码使用 HTTP REST 基本信息将数据发送到终结点。

备注

本示例要求 PowerShell v7.0 或更高版本。

  1. 运行以下示例 PowerShell 命令,该命令会为脚本添加所需程序集。

    Add-Type -AssemblyName System.Web
    
  2. 将“步骤 0”部分中的参数替换为应用程序和 DCR 中的值。 你可能还希望将“Step 2”部分中的示例数据替换为你自己的数据。

    ### Step 0: Set variables required for the rest of the script.
    
    # information needed to authenticate to AAD and obtain a bearer token
    $tenantId = "00000000-0000-0000-00000000000000000" #Tenant ID the data collection endpoint resides in
    $appId = " 000000000-0000-0000-00000000000000000" #Application ID created and granted permissions
    $appSecret = "0000000000000000000000000000000000000000" #Secret created for the application
    
    # information needed to send data to the DCR endpoint
    $endpoint_uri = "https://my-url.monitor.azure.cn" #Logs ingestion URI for the DCR
    $dcrImmutableId = "dcr-00000000000000000000000000000000" #the immutableId property of the DCR object
    $streamName = "Custom-MyTableRawData" #name of the stream in the DCR that represents the destination table
    
    
    ### Step 1: Obtain a bearer token used later to authenticate against the DCR.
    
    $scope= [System.Web.HttpUtility]::UrlEncode("https://monitor.azure.cn//.default")   
    $body = "client_id=$appId&scope=$scope&client_secret=$appSecret&grant_type=client_credentials";
    $headers = @{"Content-Type"="application/x-www-form-urlencoded"};
    $uri = "https://login.partner.microsoftonline.cn/$tenantId/oauth2/v2.0/token"
    
    $bearerToken = (Invoke-RestMethod -Uri $uri -Method "Post" -Body $body -Headers $headers).access_token
    
    
    ### Step 2: Create some sample data. 
    
    $currentTime = Get-Date ([datetime]::UtcNow) -Format O
    $staticData = @"
    [
    {
        "Time": "$currentTime",
        "Computer": "Computer1",
        "AdditionalContext": {
            "InstanceName": "user1",
            "TimeZone": "Pacific Time",
            "Level": 4,
            "CounterName": "AppMetric1",
            "CounterValue": 15.3    
        }
    },
    {
        "Time": "$currentTime",
        "Computer": "Computer2",
        "AdditionalContext": {
            "InstanceName": "user2",
            "TimeZone": "Central Time",
            "Level": 3,
            "CounterName": "AppMetric1",
            "CounterValue": 23.5     
        }
    }
    ]
    "@;
    
    
    ### Step 3: Send the data to the Log Analytics workspace.
    
    $body = $staticData;
    $headers = @{"Authorization"="Bearer $bearerToken";"Content-Type"="application/json"};
    $uri = "$endpoint_uri/dataCollectionRules/$dcrImmutableId/streams/$($streamName)?api-version=2023-01-01"
    
    $uploadResponse = Invoke-RestMethod -Uri $uri -Method "Post" -Body $body -Headers $headers
    

    备注

    如果收到 Unable to find type [System.Web.HttpUtility]. 错误,请运行脚本第 1 部分中用于修复的最后一行并执行它。 在取消注释的情况下将其作为脚本的一部分执行不能解决此问题。 必须单独执行该命令。

  3. 执行脚本,你应看到 HTTP - 204 响应。 数据应在几分钟内到达 Log Analytics 工作区。

故障排除

本部分介绍你可能会遇到的不同错误情况,以及如何更正它们。

脚本返回错误代码 403

确保你的应用程序对该 DCR 有正确的权限。 可能还需要等待长达 30 分钟的时间,权限才能传播完毕。

脚本在响应中返回错误代码 413 或 TimeoutExpired 警告以及消息 ReadyBody_ClientConnectionAbort

消息过大。 最大消息大小目前为每个调用 1 MB。

脚本返回错误代码 429

已超出 API 限制。 这些限制当前设置为每分钟 500 MB 的数据(已压缩和未压缩的数据),以及每分钟 300,000 个请求。 在响应的 Retry-After 标头中列出的持续时间过后重试。

脚本返回错误代码 503

确保你的应用程序对该 DCR 有正确的权限。 可能还需要等待长达 30 分钟的时间,权限才能传播完毕。

你未收到错误,但数据未显示在工作区中

数据可能需要一些时间才能引入,尤其是数据第一次发送到特定表时。 所需时间应不会超过 15 分钟。

Log Analytics 中的 IntelliSense 无法识别新表

用于驱动 IntelliSense 的缓存可能需要长达 24 小时的时间才能更新。

后续步骤