azure-log-analyticsazure-log-analytics-workspace

How can I create a log analytics URL that opens log analytics and runs a specified query?


I am trying to create a log analytics URL that opens log analytics and runs a query specified in the URL.

I have managed to figure out the URL scheme to be as below ( I think ) https://portal.azure.com/#blade/Microsoft_OperationsManagementSuite_Workspace/AnalyticsBlade/initiator/AnalyticsShareLinkToQuery/isQueryEditorVisible/true/scope/resources/resourceId/subscriptions/{subscriptionId}/resourcegroups/{resoruceGroup}/providers/microsoft.operationalinsights/workspaces/{workspceName}/query/QXBwUmVxdWVzdHMNCnwgdGFrZSA1/isQueryBase64Compressed/true

But it gives me an error saying that the query is in an incorrect format, I have tried it as a string, as a base64 encoded string and as a base64URL encoded string and it all gives me the same error, reading on the internet it says I need to create a compressed base 64 encoded string but I am unsure how to do this without code which is not available to me, I can only use KQL really to create the URL

Any ideas would be helpful

I tried the share copy link to query and this work but this is only for queries that have already been running in the portal once, I need to be able to pre define the query and run whatever query is specified in the URL


Solution

  • To create a log analytics URL that opens log analytics and runs a query specified in the URL:

    Use below URL format to achieve your requirement:

    $queryurl=https://portal.azure.com/#blade/Microsoft_OperationsManagementSuite_Workspace/AnalyticsBlade/initiator/AnalyticsShareLinkToQuery/isQueryEditorVisible/true/scope/resources/resourceId/subscriptions/{subscriptionId}/resourcegroups/{resoruceGroup}/providers/microsoft.operationalinsights/workspaces/{workspceName}/query/{base64Encodedquery}
    

    There is no direct way for obtaining the 'base64encodedcompressedeuery' by converting string bytes into an array. As a workaround, I found this approach, which converts the query string into bytes, stored in a memory stream and then creates a gZipStream to compress the data before converting it to an array.

    $bytes = [System.Text.Encoding]::UTF8.GetBytes($queryurl)
    $streammemory = [System.IO.MemoryStream]::new()
    $gzip = [System.IO.Compression.GZipStream]::new($streammemory, [System.IO.Compression.CompressionMode]::Compress)
    $gzip.Write($bytes, 0, $bytes.Length)
    $gzip.Close()
    $compressed = $streammemory.ToArray()
    $base64Encodedquery = [Convert]::ToBase64String($compressed)
    

    Output:

    enter image description here

    enter image description here

    You can also refer this blog by @Venkatesan Rethinam for relevant information.