azure 是否可以使用PowerShell或任何编程语言获得日志分析工作区的摄取量?

xytpbqjk  于 2023-08-07  发布在  Shell
关注(0)|答案(2)|浏览(86)

我正在获取公司日志分析工作区的摘要,其中包括每个工作区中使用的表,以及其他数据,如摄入量。
最接近“get”this的方法是在PowerShell中使用此命令

Get-AzOperationalInsightsWorkspaceUsage -ResourceGroupName "RG_name" -Name "WS_name"

字符串
它显示了这个信息:

Id            : DataAnalyzed
CurrentValue  : 0
Unit          : Bytes
Limit         : -1
NextResetTime : 7/24/2023 8:00:00 AM
QuotaPeriod   : 1.00:00:00


这是不够的,我正在寻找这个:


的数据
我搜索了类似的东西,但没有找到其他东西。希望有一个解决方案,我错过了。

voase2hg

voase2hg1#

假设您将使用您的用户帐户查询Log Analytics Rest API,并且您可以访问目标日志分析工作区**上的Az Module**和Reader角色,这就是您通过查询Usage table获取摄取量的方法。

# connect impersonating user
Connect-AzAccount
# the GUID of the LAW goes here
$workspaceId = 'xxxxx-xxxxx-xxxxx...'
$resource = 'https://api.loganalytics.io'
# get a token with permissions to query the LAW API
$token = Get-AzAccessToken -ResourceUrl $resource

$invokeRestMethodSplat = @{
    Headers     = @{
        Authorization = '{0} {1}' -f $token.Type, $token.Token
    }
    Uri         = '{0}/v1/workspaces/{1}/query' -f $resource, $workspaceId
    ContentType = 'application/json'
    Method      = 'Post'
    Body        = @{
        query = '
        Usage
        | where TimeGenerated > ago(24h)
        | summarize ["TotalIngestionVolume(GB)"] = sum(Quantity) / 1024.0 by DataType
        | order by ["TotalIngestionVolume(GB)"]
        '
    } | ConvertTo-Json
}
$response = Invoke-RestMethod @invokeRestMethodSplat

字符串
到目前为止,在$response中,您将在日志分析工作区中获得每个表的摄取量,问题是此API的响应非常糟糕,因此您必须枚举列和行以从中获取对象,如下所示:

$columns = @($response.tables.columns.name)
$result = [ordered]@{}

foreach ($row in $response.tables.rows) {
    for ($i = 0; $i -lt $columns.Count; $i++) {
        $result[$columns[$i]] = $row[$i]
    }
 
    [pscustomobject] $result
    $result.Clear()
}


如果使用Service Principal而不是模拟我们的用户帐户,逻辑几乎相同,唯一的变化是我们获取令牌的方式:

$clientId = 'xxxxx-xxxx-xxxx....'
$tenantId = 'xxxxx-xxxx-xxxx....'
$secret = 'fo0B4rB4z'

$cred = [pscredential]::new(
    $clientId,
    (ConvertTo-SecureString $secret -AsPlainText -Force))

Connect-AzAccount -ServicePrincipal -Tenant $tenantId -Credential $cred

$resource = 'https://api.loganalytics.io'
# get a token with permissions to query the LAW API
$token = Get-AzAccessToken -ResourceUrl $resource

# rest stays the same

pbwdgjma

pbwdgjma2#

你可以使用REST API来实现。您要调用的是Workspace Usages,它会以字节为单位显示您的使用情况。
https://learn.microsoft.com/en-us/rest/api/loganalytics/workspace-usages/list?tabs=HTTP#workspacelistusagesresult
您可以使用Invoke-RestMethod直接从powershell调用REST API。这是一个两步的过程。首先,您需要进行REST调用以进行身份验证,然后您可以使用在auth调用期间收到的令牌进行后续的REST调用。步骤在这里有完整的文档(这里的示例显示了如何从Powershell Context中提取令牌):
https://learn.microsoft.com/en-us/azure/governance/resource-graph/first-query-rest-api

相关问题