使用記錄擷取 API 將資料傳送至 Azure 監視器的範例程式碼
本文內容
本文提供使用記錄擷取 API 的範例程式碼。 每個範例都需要在執行程序碼之前建立下列元件。 如需建立設定為支援這些每個範例的這些元件的完整逐步解說,請參閱教學課程:使用記錄擷取 API (Resource Manager 範本) 將資料傳送至 Azure 監視器 。
Log Analytics 工作區中的自訂資料表
用於將資料導向至目標資料表的資料收集端點 (DCE)
可存取 DCR 的 Microsoft Entra 應用程式
如果您使用私人鏈接,資料收集端點 (DCE)。 否則,請使用 DCR 記錄端點。
範例指令碼
下列指令碼使用了適用於 .NET 的 Azure 監視器擷取用戶端程式庫 。
安裝 Azure 監視器擷取用戶端程式庫和 Azure 身分識別程式庫。 此範例中所使用的驗證需要 Azure 身分識別程式庫。
dotnet add package Azure.Identity
dotnet add package Azure.Monitor.Ingestion
使用您的 Microsoft Entra 應用程式的值來建立下列環境變數。 這些值會由 Azure 身分識別程式庫中的 DefaultAzureCredential
使用。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
以來自 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(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;
}
執行該程式碼,該資料應該會在幾分鐘內抵達您的 Log Analytics 工作區。
下列範例程式代碼使用適用於 Go 的 Azure 監視器擷取記錄客戶端模組。
用來 go get
安裝適用於 Go 的 Azure 監視器擷取記錄和 Azure 身分識別客戶端模組。 此範例中所使用的驗證需要 Azure 身分識別模組。
go get github.com/Azure/azure-sdk-for-go/sdk/monitor/ingestion/azlogs
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
使用您的 Microsoft Entra 應用程式的值來建立下列環境變數。 這些值會由 Azure 身分識別模組中的 DefaultAzureCredential
使用。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
以來自 DCR 的值取代下列範例程式代碼中的變數。 您可能也想要使用您自己的資料來取代範例資料。
package main
import (
"context"
"encoding/json"
"strconv"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/monitor/ingestion/azlogs"
)
// logs ingestion URI
const endpoint = "https://my-url.monitor.azure.com"
// data collection rule (DCR) immutable ID
const ruleID = "dcr-00000000000000000000000000000000"
// stream name in the DCR that represents the destination table
const streamName = "Custom-MyTableRawData"
type Computer struct {
Time time.Time
Computer string
AdditionalContext string
}
func main() {
// creating the client using DefaultAzureCredential
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
//TODO: handle error
}
client, err := azlogs.NewClient(endpoint, cred, nil)
if err != nil {
//TODO: handle error
}
// generating logs
// logs should match the schema defined by the provided stream
var data []Computer
for i := 0; i < 10; i++ {
data = append(data, Computer{
Time: time.Now().UTC(),
Computer: "Computer" + strconv.Itoa(i),
AdditionalContext: "context",
})
}
// marshal data into []byte
logs, err := json.Marshal(data)
if err != nil {
panic(err)
}
// upload logs
_, err = client.Upload(context.TODO(), ruleID, streamName, logs, nil)
if err != nil {
//TODO: handle error
}
}
執行該程式碼,該資料應該會在幾分鐘內抵達您的 Log Analytics 工作區。
下列範例程式碼使用了適用於 Java 的 Azure 監視器擷取用戶端程式庫 。
包含記錄擷取套件和 Azure 身分識別程式庫 中的 azure-identity
套件。 此範例中所使用的驗證需要 Azure 身分識別程式庫。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-monitor-ingestion</artifactId>
<version>{get-latest-version}</version>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>{get-latest-version}</version>
</dependency>
使用您的 Microsoft Entra 應用程式的值來建立下列環境變數。 這些值會由 Azure 身分識別程式庫中的 DefaultAzureCredential
使用。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
以來自 DCR 的值取代下列範例程式代碼中的變數。 您可能也想要使用您自己的資料來取代範例資料。
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.monitor.ingestion.models.LogsUploadException;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;
public class LogsUploadSample {
public static void main(String[] args) {
LogsIngestionClient client = new LogsIngestionClientBuilder()
.endpoint("https://my-url.monitor.azure.com")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
List<Object> dataList = Arrays.asList(
new Object() {
OffsetDateTime time = OffsetDateTime.now();
String computer = "Computer1";
Object additionalContext = new Object() {
String instanceName = "user4";
String timeZone = "Pacific Time";
int level = 4;
String counterName = "AppMetric1";
double counterValue = 15.3;
};
},
new Object() {
OffsetDateTime time = OffsetDateTime.now();
String computer = "Computer2";
Object additionalContext = new Object() {
String instanceName = "user2";
String timeZone = "Central Time";
int level = 3;
String counterName = "AppMetric2";
double counterValue = 43.5;
};
});
try {
client.upload("dcr-00000000000000000000000000000000", "Custom-MyTableRawData", dataList);
System.out.println("Logs uploaded successfully");
} catch (LogsUploadException exception) {
System.out.println("Failed to upload logs ");
exception.getLogsUploadErrors()
.forEach(httpError -> System.out.println(httpError.getMessage()));
}
}
}
執行該程式碼,該資料應該會在幾分鐘內抵達您的 Log Analytics 工作區。
下列範例程式碼使用了適用於 JavaScript 的 Azure 監視器擷取用戶端程式庫 。
使用 npm 安裝適用於 JavaScript 的 Azure 監視器擷取和 Azure 身分識別用戶端程式庫。 此範例中所使用的驗證需要 Azure 身分識別程式庫。
npm install --save @azure/monitor-ingestion
npm install --save @azure/identity
使用您的 Microsoft Entra 應用程式的值來建立下列環境變數。 這些值會由 Azure 身分識別程式庫中的 DefaultAzureCredential
使用。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
以來自 DCR 的值取代下列範例程式代碼中的變數。 您可能也想要使用您自己的資料來取代範例資料。
const { DefaultAzureCredential } = require("@azure/identity");
const { LogsIngestionClient, isAggregateLogsUploadError } = require("@azure/monitor-ingestion");
require("dotenv").config();
async function main() {
const logsIngestionEndpoint = "https://my-url.monitor.azure.com";
const ruleId = "dcr-00000000000000000000000000000000";
const streamName = "Custom-MyTableRawData";
const credential = new DefaultAzureCredential();
const client = new LogsIngestionClient(logsIngestionEndpoint, credential);
const logs = [
{
Time: "2021-12-08T23:51:14.1104269Z",
Computer: "Computer1",
AdditionalContext: {
"InstanceName": "user1",
"TimeZone": "Pacific Time",
"Level": 4,
"CounterName": "AppMetric2",
"CounterValue": 35.3
}
},
{
Time: "2021-12-08T23:51:14.1104269Z",
Computer: "Computer2",
AdditionalContext: {
"InstanceName": "user2",
"TimeZone": "Pacific Time",
"Level": 4,
"CounterName": "AppMetric2",
"CounterValue": 43.5
}
},
];
try{
await client.upload(ruleId, streamName, logs);
}
catch(e){
let aggregateErrors = isAggregateLogsUploadError(e) ? e.errors : [];
if (aggregateErrors.length > 0) {
console.log("Some logs have failed to complete ingestion");
for (const error of aggregateErrors) {
console.log(`Error - ${JSON.stringify(error.cause)}`);
console.log(`Log - ${JSON.stringify(error.failedLogs)}`);
}
} else {
console.log(e);
}
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
process.exit(1);
});
執行該程式碼,該資料應該會在幾分鐘內抵達您的 Log Analytics 工作區。
下列 PowerShell 程式碼會使用 HTTP REST 基礎,將資料傳送至端點。
注意
此範例需要 PowerShell v7.0 或更新版本。
執行下列範例 PowerShell 命令,以新增指令碼的必要組件。
Add-Type -AssemblyName System.Web
將步驟 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.com" #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.com//.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.microsoftonline.com/$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 區段中的最後一行,以便修正並執行。 將其取消註解做為指令碼的一部分,無法解決問題。 必須個別執行命令。
執行該指令碼,您應該會看到 HTTP - 204
回應。 該資料應該會在幾分鐘內抵達您的 Log Analytics 工作區。
下列範例程式碼使用了適用於 Python 的 Azure 監視器擷取用戶端程式庫 。
使用 pip 安裝適用於 Python 的 Azure 監視器擷取和 Azure 身分識別用戶端程式庫。 此範例中所使用的驗證需要 Azure 身分識別程式庫。
pip install azure-monitor-ingestion
pip install azure-identity
使用您的 Microsoft Entra 應用程式的值來建立下列環境變數。 這些值會由 Azure 身分識別程式庫中的 DefaultAzureCredential
使用。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
以來自 DCR 的值取代下列範例程式代碼中的變數。 您也可以您自己的資料取代 [Step 2] 區段中的範例資料。
# information needed to send data to the DCR endpoint
endpoint_uri = "https://my-url.monitor.azure.com" # logs ingestion endpoint of the DCR
dcr_immutableid = "dcr-00000000000000000000000000000000" # immutableId property of the Data Collection Rule
stream_name = "Custom-MyTableRawData" #name of the stream in the DCR that represents the destination table
# Import required modules
import os
from azure.identity import DefaultAzureCredential
from azure.monitor.ingestion import LogsIngestionClient
from azure.core.exceptions import HttpResponseError
credential = DefaultAzureCredential()
client = LogsIngestionClient(endpoint=endpoint_uri, credential=credential, logging_enable=True)
body = [
{
"Time": "2023-03-12T15:04:48.423211Z",
"Computer": "Computer1",
"AdditionalContext": {
"InstanceName": "user1",
"TimeZone": "Pacific Time",
"Level": 4,
"CounterName": "AppMetric2",
"CounterValue": 35.3
}
},
{
"Time": "2023-03-12T15:04:48.794972Z",
"Computer": "Computer2",
"AdditionalContext": {
"InstanceName": "user2",
"TimeZone": "Central Time",
"Level": 3,
"CounterName": "AppMetric2",
"CounterValue": 43.5
}
}
]
try:
client.upload(rule_id=dcr_immutableid, stream_name=stream_name, logs=body)
except HttpResponseError as e:
print(f"Upload failed: {e}")
執行該程式碼,該資料應該會在幾分鐘內抵達您的 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 小時才能更新。
下一步