你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

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

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

  • Log Analytics 工作区中的自定义表
  • 用于接收数据的数据收集终结点(DCE)
  • 用于将数据定向到目标表的数据收集规则(DCR)
  • 有权访问 DCR 的 Microsoft Entra 应用程序

示例代码

以下脚本使用 适用于 .NET 的 Azure Monitor 引入客户端库

  1. 安装 Azure Monitor 引入客户端库和 Azure 标识库。 此示例中使用的身份验证需要 Azure 标识库。

    dotnet add package Azure.Identity
    dotnet add package Azure.Monitor.Ingestion
    
  2. 使用 Microsoft Entra 应用程序的值创建以下环境变量。 这些值在 Azure 标识库中由 DefaultAzureCredential 使用。

    • AZURE_TENANT_ID
    • AZURE_CLIENT_ID
    • AZURE_CLIENT_SECRET
  3. 将以下示例代码中的变量替换为 DCE 和 DCR 中的值。 你可能还想要将示例数据替换为自己的数据。

    using Azure;
    using Azure.Core;
    using Azure.Identity;
    using Azure.Monitor.Ingestion;
    
    // Initialize variables
    var endpoint = new Uri("https://logs-ingestion-rzmk.eastus2-1.ingest.monitor.azure.com");
    var ruleId = "dcr-00000000000000000000000000000000";
    var streamName = "Custom-MyTableRawData";
    
    // Create credential and client
    var credential = new DefaultAzureCredential();
    LogsIngestionClient client = new(endpoint, credential);
    
    DateTimeOffset currentTime = DateTimeOffset.UtcNow;
    
    // Use BinaryData to serialize instances of an anonymous type into JSON
    BinaryData data = BinaryData.FromObjectAsJson(
        new[] {
            new
            {
                Time = currentTime,
                Computer = "Computer1",
                AdditionalContext = new
                {
                    InstanceName = "user1",
                    TimeZone = "Pacific Time",
                    Level = 4,
                    CounterName = "AppMetric1",
                    CounterValue = 15.3
                }
            },
            new
            {
                Time = currentTime,
                Computer = "Computer2",
                AdditionalContext = new
                {
                    InstanceName = "user2",
                    TimeZone = "Central Time",
                    Level = 3,
                    CounterName = "AppMetric1",
                    CounterValue = 23.5
                }
            },
        });
    
    // Upload logs
    try
    {
        Response response = client.Upload(ruleId, streamName, RequestContent.Create(data));
    }
    catch (Exception ex)
    {
        Console.WriteLine("Upload failed with Exception " + ex.Message);
    }
    
    // Logs can also be uploaded in a List
    var entries = new List<Object>();
    for (int i = 0; i < 10; i++)
    {
        entries.Add(
            new {
                Time = recordingNow,
                Computer = "Computer" + i.ToString(),
                AdditionalContext = i
            }
        );
    }
    
    // Make the request
    LogsUploadOptions options = new LogsUploadOptions();
    bool isTriggered = false;
    options.UploadFailed += Options_UploadFailed;
    await client.UploadAsync(TestEnvironment.DCRImmutableId, TestEnvironment.StreamName, entries, options).ConfigureAwait(false);
    
    Task Options_UploadFailed(LogsUploadFailedEventArgs e)
    {
        isTriggered = true;
        Console.WriteLine(e.Exception);
        foreach (var log in e.FailedLogs)
        {
            Console.WriteLine(log);
        }
        return Task.CompletedTask;
    }
    
  4. 执行代码,数据应在几分钟内到达 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 小时的时间才能更新。

后续步骤