로그 수집 API를 사용하여 Azure Monitor로 데이터를 보내는 샘플 코드
이 문서의 내용
이 문서에서는 로그 수집 API 를 사용하는 샘플 코드를 제공합니다. 각 샘플에서는 코드를 실행하기 전에 다음 구성 요소를 만들어야 합니다. 이러한 각 샘플을 지원하도록 구성된 구성 요소를 만드는 전체 연습은 자습서: 로그 수집 API(Resource Manager 템플릿)를 사용하여 Azure Monitor에 데이터 보내기 를 참조하세요.
Log Analytics 작업 영역의 사용자 지정 테이블
데이터를 수신하는 DCE(데이터 컬렉션 엔드포인트)
데이터를 대상 테이블로 전달하는 DCR(데이터 수집 규칙)
DCR에 대한 액세스 권한이 있는 Microsoft Entra 애플리케이션
샘플 코드
다음 스크립트는 .NET용 Azure Monitor 수집 클라이언트 라이브러리 를 사용합니다.
Azure Monitor 수집 클라이언트 라이브러리 및 Azure ID 라이브러리를 설치합니다. 이 샘플에서 사용되는 인증에는 Azure ID 라이브러리가 필요합니다.
dotnet add package Azure.Identity
dotnet add package Azure.Monitor.Ingestion
Microsoft Entra 애플리케이션에 대한 값을 사용하여 다음 환경 변수를 만듭니다. 이러한 값은 Azure ID 라이브러리에서 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 수집 로그 클라이언트 모듈 을 사용합니다.
go get
을 사용하여 Go용 Azure Monitor 수집 로그 및 Azure ID 클라이언트 모듈을 설치합니다. 이 샘플에서 사용되는 인증에는 Azure ID 모듈이 필요합니다.
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 ID 모듈에서 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 수집 클라이언트 라이브러리 를 사용합니다.
azure-identity
Azure ID 라이브러리의 로그 수집 패키지 및 패키지를 포함합니다. 이 샘플에서 사용되는 인증에는 Azure ID 라이브러리가 필요합니다.
<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 ID 라이브러리에서 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 수집 클라이언트 라이브러리 를 사용합니다.
npm 을 사용하여 JavaScript용 Azure Monitor 수집 및 Azure ID 클라이언트 라이브러리를 설치합니다. 이 샘플에서 사용되는 인증에는 Azure ID 라이브러리가 필요합니다.
npm install --save @azure/monitor-ingestion
npm install --save @azure/identity
Microsoft Entra 애플리케이션에 대한 값을 사용하여 다음 환경 변수를 만듭니다. 이러한 값은 Azure ID 라이브러리에서 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
0단계 섹션의 매개 변수를 애플리케이션, DCE 및 DCR의 값으로 바꿉니다. 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 수집 클라이언트 라이브러리 를 사용합니다.
pip 를 사용하여 Python용 Azure Monitor 수집 및 Azure ID 클라이언트 라이브러리를 설치합니다. 이 샘플에서 사용되는 인증에는 Azure ID 라이브러리가 필요합니다.
pip install azure-monitor-ingestion
pip install azure-identity
Microsoft Entra 애플리케이션에 대한 값을 사용하여 다음 환경 변수를 만듭니다. 이러한 값은 Azure ID 라이브러리에서 DefaultAzureCredential
에 의해 사용됩니다.
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
다음 샘플 코드의 변수를 DCE 및 DCR의 값으로 바꿉니다. 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와 함께 반환합니다.
메시지가 너무 큽니다. 최대 메시지 크기는 현재 호출당 1MB입니다.
스크립트가 오류 코드 429를 반환합니다.
API 한도를 초과했습니다. 현재 제한은 압축 및 비압축 데이터 모두에 대해 분당 500MB의 데이터와 분당 300,000개의 요청으로 설정되어 있습니다. 응답의 Retry-After
머리글에 나열된 기간 후에 다시 시도합니다.
스크립트가 오류 코드 503을 반환합니다.
DCR에 대한 애플리케이션에 대한 올바른 권한이 있는지 확인합니다. 권한이 전파될 때까지 최대 30분을 기다려야 할 수도 있습니다.
오류가 발생하지 않지만 작업 영역에 데이터가 표시되지 않습니다.
데이터를 수집하는 데 시간이 걸릴 수 있습니다. 특히 데이터가 특정 테이블에 처음 전송되는 경우 더 그럴 수 있습니다. 15분 이상 걸리지는 않습니다.
Log Analytics의 IntelliSense가 새 테이블을 인식하지 못합니다.
IntelliSense를 구동하는 캐시는 업데이트하는 데 최대 24시간이 걸릴 수 있습니다.
다음 단계