共用方式為


使用記錄擷取 API 將資料傳送至 Azure 監視器的範例程式碼

本文提供使用記錄擷取 API 的範例程式碼。 每個範例都需要在執行程序碼之前建立下列元件。 如需完整逐步解說這些元件的建立與設定以支援每一個範例,請參閱 教學課程:使用記錄擷取 API (Resource Manager 模板) 將資料傳送至 Azure 監控

  • Log Analytics 工作區中的自訂資料表
  • 用於將資料導向至目標資料表的資料收集規則 (DCR)
  • 可存取 DCR 的 Microsoft Entra 應用程式
  • 資料收集端點 (DCE) (如果您使用私人連結)。 否則,請使用 DCR 記錄端點。

範例指令碼

下列指令碼使用了適用於 .NET 的 Azure 監視器擷取用戶端程式庫

  1. 安裝 Azure 監視器擷取用戶端程式庫和 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 工作區。

疑難排解

本節描述您可能會收到的不同錯誤狀況,以及更正的方式。

錯誤 說明
錯誤碼 403 請確保您的應用程式具有 DCR 的正確權限。 您也可能需要等候最多 30 分鐘,讓權限完成散佈。
錯誤碼 413 或回應中具有訊息 TimeoutExpiredReadyBody_ClientConnectionAbort 警告 訊息太大。 每個呼叫的訊息大小上限目前為 1 MB。
錯誤碼 RecordsTimeRangeIsMoreThan30Minutes 這是一個 已知的限制 ,即將被刪除。 此限制不適用於使用 轉換的輔助日誌。
錯誤碼 429 已超過 API 限制。 目前,壓縮和未壓縮資料的限制設定為每分鐘 500 MB 的資料,以及每分鐘 300,000 個要求。 請在回應的 Retry-After 標頭中列出的持續時間後重試。
無資料 資料可能需要一些時間才能擷取,特別是第一次將資料傳送至特定資料表時。 其不應該花費超過 15 分鐘的時間。
Log Analytics 中的 IntelliSense 無法辨識新的數據表。 驅動 IntelliSense 的快取最多可能需要 24 小時才能更新。

下一步