首页 > 解决方案 > 将 Log Analytics 工作区查询的结果输出到事件中心

问题描述

我正在执行查询以输出在 Azure Log Analytics 工作区中捕获的日志,例如: Invoke-AzOperationalInsightsQuery -WorkspaceId '' -Query "AzureDiagnostics | where Category == 'AzureFirewallApplicationRule'"

但是,我需要将此结果发送到事件中心以进行进一步处理。

我正在尝试使用 REST API ( https://docs.microsoft.com/en-us/rest/api/eventhub/send-batch-events ) 但努力动态生成请求正文以发送到事件中心基于查询的输出字段。这可能不是最好的方法,有什么建议吗?

标签: azure-powershellazure-eventhubazure-log-analytics

解决方案


我建议你可以通过一个一个发送一个简单的json数据来使用Send event api。因为如果你使用发送批处理 api,你应该构建一个更复杂的源数据。

您可以使用以下 powershell 代码通过发送事件api 将数据发送到事件中心。

$queryResults = Invoke-AzOperationalInsightsQuery -WorkspaceId "xxx" -Query "your query"    

#generate sas token
$URI_1 = "event_hub_namespace.servicebus.windows.net/eventhub_path"
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="the key"

#Token expires now+3000
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+3000
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI_1)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI_1) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name
$SASToken

$method = "POST"
$url = "https://event_hub_namespace.servicebus.windows.net/eventhub_path/messages"
$signature = $SASToken

# API headers
$headers = @{
            "Authorization"=$signature;
            "Content-Type"="application/atom+xml;type=entry;charset=utf-8";
            }

#use foreach to send data
foreach($s in $queryResults.Results){
    #Write-Output "hello"
    $json = $s | ConvertTo-Json
    #Write-Output $json

    Invoke-WebRequest -Method $method -Headers $headers -Body $json -uri $url
}

Write-Output "**completed**"

执行 powershell后,我使用代码从事件中心接收数据,我可以确认所有数据都发送到事件中心。截图如下:

在此处输入图像描述


推荐阅读