azureazure-powershellazure-log-analyticsazure-python-sdkazure-log-analytics-workspace

How to get log analytics workspace usage details via api


I want to fetch the usage details for each month of an azure log analytics workspace, same as below. Is there any API or which 'metric' that can be used to get the details? I checked the 'ingestion volume' metric - but the data is not matching.

enter image description here


Solution

  • Try using log analytics query rest api to query Usage table, it works well at my side.

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$WorkspaceId,
        [Parameter(Mandatory)]
        [string]$TenantId,
        [Parameter(Mandatory)]
        [string]$ClientId,
        [Parameter(Mandatory)]
        [string]$ClientSecret
    )
    
    $headers = @{
        "Content-Type" = "application/x-www-form-urlencoded"
    }
    
    $uri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
    
    $body = @{
        grant_type    = "client_credentials"
        resource      = 'https://api.loganalytics.io'
        client_id     = $ClientId
        client_secret = $ClientSecret
    }
    
    $token = Invoke-RestMethod -Method Post -Uri $uri -Body $body -Headers $headers
    
    
    $headers1 = @{
        "Content-Type" = "application/json"
        "Authorization" = "Bearer " + $token.access_token
    }
    
    $uri1 = "https://api.loganalytics.io/v1/workspaces/$WorkspaceId/query"
    
    $queryString = "Usage | where TimeGenerated  > startofday(ago(31d)) | where IsBillable == true | extend isSecurity = DataType in ('WindowsEvent','SecurityAlert','SecurityBaseline','SecurityBaselineSummary','SecurityDetection','SecurityEvent','WindowsFirewall','MaliciousIPCommunication','LinuxAuditLog','SysmonEvent','ProtectionStatus') | summarize TotalVolumeGB = sum(Quantity) / 1000 by bin(TimeGenerated, 1d), isSecurity, DataType| sort by TimeGenerated asc"
    
    $body1 = @{
        query = $QueryString
    }
    
    $bodyString = $body1 | ConvertTo-Json -Depth 10
    
    $response = Invoke-RestMethod -Method Post -Uri $uri1 -Body $bodyString -Headers $headers1
    
    $response
    

    enter image description here