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

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

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

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

示例代码

以下脚本使用 适用于 .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. 将以下示例代码中的变量替换为 DCR 中的值。 你可能还想要将示例数据替换为自己的数据。

using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.Monitor.Ingestion;

// Initialize variables
var endpoint = new Uri("https://my-url.monitor.azure.com");
var ruleId = "dcr-00000000000000000000000000000000";
var streamName = "Custom-MyTableRawData";

// Create credential and client
var credential = new DefaultAzureCredential();
LogsIngestionClient client = new LogsIngestionClient(endpoint, credential);

DateTime currentTime = DateTime.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
{
   // ===== START: Use this block of code to upload compressed data
   byte[] dataBytes = data.ToArray();
   
   string contentEncoding = "gzip"; // Specify gzip if the content is already compressed

   using (MemoryStream memoryStream = new MemoryStream())
   {
    using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress))
    {
       gzipStream.Write(dataBytes, 0, dataBytes.Length);
    }
    byte[] gzipBytes = memoryStream.ToArray();

    var response = await client.UploadAsync(ruleId, streamName, RequestContent.Create(gzipBytes), contentEncoding).ConfigureAwait(false);
    if (response.IsError)
    {
       throw new Exception(response.ToString());
    }
   }
   // ===== End: code block to upload compressed data
 
   //** ===== START: Use this block of code to upload uncompressed data.
   var response = await client.UploadAsync(ruleId, streamName, RequestContent.Create(data)).ConfigureAwait(false);
   if (response.IsError)
   {
    throw new Exception(response.ToString());
   }
   //** ===== End: code block to upload uncompressed data.

}
catch (Exception ex)
{
    Console.WriteLine("Upload failed with Exception: " + ex.Message);
}
  1. 执行代码,数据应在几分钟内到达 Log Analytics 工作区。

疑难解答

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

错误 Description
错误代码 403 确保你的应用程序对该 DCR 有正确的权限。 可能还需要等待长达 30 分钟的时间,权限才能传播完毕。
响应中消息 ReadyBody_ClientConnectionAbort 的错误代码 413 或警告 TimeoutExpired 消息过大。 最大消息大小目前为每个调用 1 MB。
错误代码 RecordsTimeRangeIsMoreThan30Minutes 这是一个正在被删除的已知限制。 此限制不适用于使用 转换的辅助日志。
错误代码 429 已超出 API 限制。 这些限制当前设置为每分钟 500 MB 的数据(已压缩和未压缩的数据),以及每分钟 300,000 个请求。 在响应的 Retry-After 标头中列出的持续时间过后重试。
无数据 数据可能需要一些时间才能引入,尤其是数据第一次发送到特定表时。 所需时间应不会超过 15 分钟。
Log Analytics 中的 IntelliSense 无法识别新表。 用于驱动 IntelliSense 的缓存可能需要长达 24 小时的时间才能更新。

Next steps