Azure Monitor Query

2.0.0 · active · verified Thu Apr 09

The Azure Monitor Query client library for Python provides functionality to query logs and metrics data from Azure Monitor. It is part of the Azure SDK for Python, currently at version 2.0.0, and follows the Azure SDK's monthly release cadence for minor updates and bug fixes, with major versions introducing significant changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate using `DefaultAzureCredential` and query logs from a Log Analytics Workspace using `LogsQueryClient`. It executes a simple KQL query to fetch the last 5 Azure Activity logs within the last hour. Remember to replace `YOUR_LOG_ANALYTICS_WORKSPACE_ID` or set the environment variable.

import os
from datetime import datetime, timedelta
from azure.monitor.query import LogsQueryClient, QueryTimeInterval
from azure.identity import DefaultAzureCredential

# Replace with your Log Analytics Workspace ID
# or set LOG_ANALYTICS_WORKSPACE_ID environment variable
workspace_id = os.environ.get('LOG_ANALYTICS_WORKSPACE_ID', 'YOUR_LOG_ANALYTICS_WORKSPACE_ID')

if workspace_id == 'YOUR_LOG_ANALYTICS_WORKSPACE_ID':
    print("Please set the LOG_ANALYTICS_WORKSPACE_ID environment variable or replace the placeholder.")
    exit(1)

try:
    credential = DefaultAzureCredential()
    client = LogsQueryClient(credential)

    # Define the Kusto Query Language (KQL) query
    query = "AzureActivity | take 5"

    # Define the time interval for the query
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=1)
    time_interval = QueryTimeInterval(start_time=start_time, end_time=end_time)

    print(f"Executing query for workspace {workspace_id}...")
    response = client.query_workspace(
        workspace_id=workspace_id,
        query=query,
        timespan=time_interval
    )

    for table in response.tables:
        print(f"\nTable: {table.name}")
        print("-" * len(f"Table: {table.name}"))
        # Print columns (optional)
        # for col in table.columns:
        #     print(f"  Column: {col.name} ({col.type})")
        
        # Print rows
        for row in table.rows:
            print(f"  Row: {row}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure you have set up credentials (e.g., AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) ")
    print("or authenticated via Azure CLI and have permissions to access the workspace.")

view raw JSON →