PowerShell ile Log Analytics Workspace’e Özel Log Göndermek

Azure Log Analytics yalnızca Azure kaynaklarından değil, özel uygulamalarınızdan da log verisi kabul eder. PowerShell ile HTTP Data Collector API’sini kullanarak kendi verilerinizi gönderebilirsiniz.

HMAC İmzalama Fonksiyonu

PowerShell
function Build-LASignature {
    param($workspaceId, $sharedKey, $date, $contentLength, $method, $contentType, $resource)
    $xHeaders = "x-ms-date:" + $date
    $stringToHash = "$method`n$contentLength`n$contentType`n$xHeaders`n$resource"
    $bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
    $keyBytes    = [Convert]::FromBase64String($sharedKey)
    $sha256      = New-Object System.Security.Cryptography.HMACSHA256
    $sha256.Key  = $keyBytes
    $encodedHash = [Convert]::ToBase64String($sha256.ComputeHash($bytesToHash))
    return "SharedKey " + $workspaceId + ":" + $encodedHash
}
 

Log Göndermek

PowerShell
function Send-LAData {
    param($workspaceId, $sharedKey, $body, $logType)
    $date     = [DateTime]::UtcNow.ToString("r")
    $length   = ([Text.Encoding]::UTF8.GetBytes($body)).Length
    $sig      = Build-LASignature $workspaceId $sharedKey $date $length "POST" "application/json" "/api/logs"
    $uri      = "https://$workspaceId.ods.opinsights.azure.com/api/logs?api-version=2016-04-01"
    $headers  = @{ Authorization = $sig; "Log-Type" = $logType; "x-ms-date" = $date }
    Invoke-WebRequest -Uri $uri -Method Post -ContentType "application/json" -Headers $headers -Body $body
}
 
$data = @(@{ Sunucu = "WEB01"; Durum = "OK"; Gecikme = 120 }) | ConvertTo-Json
Send-LAData -workspaceId "$workspaceid" -sharedKey "$primarykey" -body $data -logType "CustomAppLogs_CL" | out-null
Write-Host "Log gönderildi." -ForegroundColor Green