Logs ingestion API を使用して Azure Monitor にデータを送信するサンプル コード
[アーティクル] 04/15/2024
5 人の共同作成者
フィードバック
この記事の内容
この記事では、Logs ingestion API を使用したサンプル コードについて説明します。 各サンプルでは、コードを実行する前に、次のコンポーネントを作成する必要があります。 これらの各サンプルをサポートするように構成されたこれらのコンポーネントを作成する完全なチュートリアルについては、「チュートリアル: Logs ingestion API (Resource Manager テンプレート) を使って Azure Monitor にデータを送信する 」を参照してください。
Log Analytics ワークスペースのカスタム テーブル
データを受信するためのデータ収集エンドポイント (DCE)
データをターゲット テーブルに転送するためのデータ収集ルール (DCR)
DCR にアクセスできる Microsoft Entra アプリケーション
サンプル コード
次のスクリプトでは、.NET 用 Azure Monitor Ingestion クライアント ライブラリ を使用しています。
Azure Monitor Ingestion クライアント ライブラリと Azure Identity ライブラリをインストールします。 このサンプルで使用される認証には、Azure Identity ライブラリが必要です。
dotnet add package Azure.Identity
dotnet add package Azure.Monitor.Ingestion
Microsoft Entra アプリケーションの値を使用して、次の環境変数を作成します。 これらの値は、Azure Identity ライブラリの DefaultAzureCredential
で使用されます。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
次のサンプル コードの変数を、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;
}
コードを実行します。データは数分以内に Log Analytics ワークスペースに到着するはずです。
次のサンプル コードでは、Go 用 Azure Monitor Ingestion ログ クライアント モジュール を使用しています。
go get
を使用して、Go 用 Azure Monitor Ingestion ログおよび Azure Identity クライアント モジュールをインストールします。 このサンプルで使用される認証には、Azure Identity モジュールが必要です。
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 Identity モジュールの DefaultAzureCredential
で使用されます。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
次のサンプル コードの変数を、DCE および 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"
)
// data collection endpoint (DCE)
const endpoint = "https://logs-ingestion-rzmk.eastus2-1.ingest.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 Monitor Ingestion クライアント ライブラリ を使用しています。
Logs ingestion パッケージと、Azure Identity ライブラリ の azure-identity
パッケージを組み込みます。 このサンプルで使用される認証には、Azure Identity ライブラリが必要です。
<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 Identity ライブラリの DefaultAzureCredential
で使用されます。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
次のサンプル コードの変数を、DCE および 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://logs-ingestion-rzmk.eastus2-1.ingest.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 Monitor Ingestion クライアント ライブラリ を使用しています。
npm を使用して、JavaScript 用 Azure Monitor Ingestion および Azure Identity クライアント ライブラリをインストールします。 このサンプルで使用される認証には、Azure Identity ライブラリが必要です。
npm install --save @azure/monitor-ingestion
npm install --save @azure/identity
Microsoft Entra アプリケーションの値を使用して、次の環境変数を作成します。 これらの値は、Azure Identity ライブラリの DefaultAzureCredential
で使用されます。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
次のサンプル コードの変数を、DCE および DCR の値に置き換えます。 サンプル データも独自のものに置き換えることをお勧めします。
const { DefaultAzureCredential } = require("@azure/identity");
const { LogsIngestionClient, isAggregateLogsUploadError } = require("@azure/monitor-ingestion");
require("dotenv").config();
async function main() {
const logsIngestionEndpoint = "https://logs-ingestion-rzmk.eastus2-1.ingest.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
Step 0 セクションのパラメーターを、アプリケーション、DCE、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
$dceEndpoint = "https://logs-ingestion-rzmk.eastus2-1.ingest.monitor.azure.com" #the endpoint property of the Data Collection Endpoint object
$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 DCE.
$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 via the DCE.
$body = $staticData;
$headers = @{"Authorization"="Bearer $bearerToken";"Content-Type"="application/json"};
$uri = "$dceEndpoint/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 Monitor Ingestion クライアント ライブラリ を使用しています。
pip を使用して、Python 用 Azure Monitor Ingestion および Azure Identity クライアント ライブラリをインストールします。 このサンプルで使用される認証には、Azure Identity ライブラリが必要です。
pip install azure-monitor-ingestion
pip install azure-identity
Microsoft Entra アプリケーションの値を使用して、次の環境変数を作成します。 これらの値は、Azure Identity ライブラリの DefaultAzureCredential
で使用されます。
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
次のサンプル コードの変数を、DCE および DCR の値に置き換えます。 Step 2 セクションのサンプル データを独自のものに置き換えることもできます。
# information needed to send data to the DCR endpoint
dce_endpoint = "https://logs-ingestion-rzmk.eastus2-1.ingest.monitor.azure.com" # ingestion endpoint of the Data Collection Endpoint object
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=dce_endpoint, 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 回の呼び出しで現在 1 MB です。
スクリプトでエラー コード 429 が返される
API の制限を超えました。 現在、設定されている制限は、圧縮データと非圧縮データの両方について 500 MB/分と 300,000 要求/分です。 応答の Retry-After
ヘッダーに示されている期間の後に再試行します。
スクリプトでエラー コード 503 が返される
DCR に対する適切なアクセス許可がアプリケーションにあることを確認します。 また、アクセス許可が反映されるまでに最大 30 分待つ必要がある場合もあります。
エラーは発生しないが、データがワークスペースに表示されない
特にデータが特定のテーブルに初めて送信される場合は、データが取り込まれるまでに時間がかかることがあります。 15 分を超えることはありません。
Log Analytics の IntelliSense で新しいテーブルが認識されない
IntelliSense を動作させるキャッシュは、更新に最大 24 時間かかる場合があります。
次のステップ