메트릭 제출: PowerShell
Datadog은 어떤 언어를 사용하든 Agent와 API 양쪽에서 메트릭을 수집할 수 있어요. 이 문서에서는 두 가지 방법을 PowerShell로 구현한 예시를 소개해요. Agent 없이 API를 직접 호출하는 방식과, Agent의 DogStatsD 리스너를 활용하는 방식을 함께 살펴봐요.
출처: 문서
본문
Datadog은 어떤 언어를 사용하든 Agent뿐 아니라 API에서도 메트릭을 수집할 수 있어요. 이 페이지에서는 두 가지를 모두 PowerShell로 구현한 예시를 보여줘요.
API로 PowerShell로 메트릭 제출하기
이 방법은 PowerShell 스크립트가 실행되는 시스템에 Agent를 설치할 필요가 없어요. POST 요청을 보낼 때 API 키와 애플리케이션 키(application key)를 명시적으로 전달해야 해요.
# This script sends a custom metric to Datadog v2 API from PowerShell.
# Tested on Windows 10 Pro (version 10.0.1945) with PSVersion 5.1 (Build 19041, Revision 5486)
function Send-DatadogMetric {
param(
[Parameter(Mandatory=$true)]
[string]$MetricName,
[Parameter(Mandatory=$true)]
[int]$MetricValue,
[Parameter(Mandatory=$false)]
[string[]]$Tags = @()
)
# ==================================
# 1) Set Datadog API keys (v2)
# ==================================
# - $url: The API endpoint for sending metric data to Datadog.
# By default, it is set to the US1 data center. If you are
# operating in a different region, update this URL accordingly:
# * EU: https://api.datadoghq.eu/api/v2/series
# * US3: https://api.us3.datadoghq.com/api/v2/series
# * US5: https://api.us5.datadoghq.com/api/v2/series
# * AP1: https://api.ap1.datadoghq.com/api/v2/series
# * AP2: https://api.ap2.datadoghq.com/api/v2/series
# * US1-FED: https://api.ddog-gov.com/api/v2/series
# * US2-FED: https://api.us2.ddog-gov.com/api/v2/series
$api_key = "<DATADOG_API_KEY>" #provide your valid api key
$app_key = "<DATADOG_APPLICATION_KEY>" #provide your valid app key
$url = "https://api.datadoghq.com/api/v2/series" # Default endpoint for US1; update based on your Datadog data center
# ==================================
# 2) Request headers
# ==================================
$headers = @{
"DD-API-KEY" = $api_key
"DD-APPLICATION-KEY" = $app_key
"Content-Type" = "application/json"
}
# ==================================
# 3) Build JSON payload for v2
# ==================================
# Current time in epoch seconds
$currentTime = [int](Get-Date -date ((get-date).ToUniversalTime()) -UFormat %s) -Replace("[,\.]\d*", "")
# The body for the /api/v2/series endpoint
$body = @{
"series" = @(
@{
"metric" = $MetricName
"points" = @(
@{
"timestamp" = $currentTime
"value" = $MetricValue
}
)
"type" = 1 # (1) count, (2) rate, (3) gauge
"tags" = $Tags # optional parameter should be an array of tags
}
)
}
# Convert hash to JSON
$jsonBody = $body | ConvertTo-Json -Depth 5 -Compress
# ==================================
# 4) Send the POST request
# ==================================
$response = Invoke-RestMethod -Method Post -Uri $url -Headers $headers -Body $jsonBody
Write-Host "Datadog response: $($response | ConvertTo-Json -Depth 5)"
}
# ----------------------------
# Example Usage:
# ----------------------------
# This sends a custom count metric called "my.custom.metric" with a value of 42
# and adds "env:test" + "version:1.0" + host as tags.
Send-DatadogMetric -MetricName "my.custom.metric" `
-MetricValue 42 `
-Tags @("env:test","version:1.0", "host:$env:COMPUTERNAME")
DogStatsD로 PowerShell로 메트릭 제출하기
Agent가 있으면 Agent의 DogStatsD 리스너를 사용할 수 있어요. 다음 예시는 동일한 메트릭을 DogStatsD로 보내는 방법을 보여줘요. API 키나 애플리케이션 키를 더 이상 지정할 필요가 없다는 점에 주목하세요. 이미 로컬 datadog.yaml에 있기 때문이에요.
# Tested on Windows Server 2012 R2 w/ PSVersion 4.0
# Windows Server 2008 x64 R2 w/ PSVersion 2.0
function dogstatsd($metric) {
$udpClient = New-Object System.Net.Sockets.UdpClient
$udpClient.Connect('127.0.0.1', '8125')
$encodedData=[System.Text.Encoding]::ASCII.GetBytes($metric)
$bytesSent=$udpClient.Send($encodedData,$encodedData.Length)
$udpClient.Close()
}
$tags = "|#env:test" # Datadog tag
$temp = Get-Process mmc
$metric = "dogstatsd.ps1." + $temp.Name + ":" + $temp.Handles + "|g" + $tags # metric
dogstatsd($metric)
예시
Mozilla 문서에 완전히 문서화된 Msxml2.XMLHTTP를 사용해 PowerShell로 번역한 두 가지 예시를 소개할게요.
API 호출을 수행하는 코드
$url_base = "https://app.datadoghq.com/"
$url = $url_base + $url_signature + "?api_key=$api_key" + "&" + "application_key=$app_key"
$http_request = New-Object -ComObject Msxml2.XMLHTTP
$http_request.open($http_method, $url, $false)
$http_request.setRequestHeader("Content-type", "application/json")
$http_request.setRequestHeader("Connection", "close")
$http_request.send($parameters)
$http_request.status
$http_request.responseText
호스트에 태그 추가하기
-
API/앱 키를 본인 것으로 교체하세요.
$api_key = "<DATADOG_API_KEY>" $app_key = "<DATADOG_APPLICATION_KEY>" -
호스트 API의 설명에 따라 파라미터를 설정하세요.
$host_name = "test.host" $http_method = "POST" $url_signature = "api/v1/tags/hosts/$host_name" $parameters = "{ `"tags`" : [`"environment:production`", `"role:webserver`"] }" -
첫 번째 섹션에 있는 코드를 실행하세요.
메트릭 전송하기
-
API/앱 키를 본인 것으로 교체하세요.
$api_key = "<DATADOG_API_KEY>" $app_key = "<DATADOG_APPLICATION_KEY>" -
metrics API의 설명에 따라 파라미터를 설정하세요.
$http_method = "POST" $url_signature = "api/v2/series" $currenttime = (Get-Date -date ((get-date).ToUniversalTime()) -UFormat %s) -Replace("[,\.]\d*", "") $parameters = "{ `"series`" : [{`"metric`":`"test.powershell`", `"points`":[[$currenttime, 20]], `"type`":`"gauge`", `"host`":`"test.example.com`", `"tags`":[`"environment:test`"]} ] }" -
첫 번째 섹션에 있는 코드를 실행하세요.
ncracker/dd_metric GitHub 리포지토리에서 더 많은 코드 예시를 확인할 수 있어요.
더 알아보기 (Learn more)
추가로 도움이 되는 문서, 링크, 글: