{"id":1388,"library":"azure-monitor-query","title":"Azure Monitor Query","description":"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.","status":"active","version":"2.0.0","language":"en","source_language":"en","source_url":"https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-query","tags":["azure","monitor","logs","metrics","cloud","observability"],"install":[{"cmd":"pip install azure-monitor-query azure-identity","lang":"bash","label":"Install with identity"}],"dependencies":[{"reason":"Required for Azure Active Directory authentication, which is the recommended way to authenticate with Azure services.","package":"azure-identity","optional":true}],"imports":[{"symbol":"LogsQueryClient","correct":"from azure.monitor.query import LogsQueryClient"},{"symbol":"MetricsQueryClient","correct":"from azure.monitor.query import MetricsQueryClient"},{"note":"In v2.0.0, the `timespan` parameter for query methods often expects a `QueryTimeInterval` object or a string, not raw datetime/timedelta tuples like in v1.","wrong":"from datetime import datetime, timedelta # for timespan directly","symbol":"QueryTimeInterval","correct":"from azure.monitor.query import QueryTimeInterval"},{"symbol":"DefaultAzureCredential","correct":"from azure.identity import DefaultAzureCredential"}],"quickstart":{"code":"import os\nfrom datetime import datetime, timedelta\nfrom azure.monitor.query import LogsQueryClient, QueryTimeInterval\nfrom azure.identity import DefaultAzureCredential\n\n# Replace with your Log Analytics Workspace ID\n# or set LOG_ANALYTICS_WORKSPACE_ID environment variable\nworkspace_id = os.environ.get('LOG_ANALYTICS_WORKSPACE_ID', 'YOUR_LOG_ANALYTICS_WORKSPACE_ID')\n\nif workspace_id == 'YOUR_LOG_ANALYTICS_WORKSPACE_ID':\n    print(\"Please set the LOG_ANALYTICS_WORKSPACE_ID environment variable or replace the placeholder.\")\n    exit(1)\n\ntry:\n    credential = DefaultAzureCredential()\n    client = LogsQueryClient(credential)\n\n    # Define the Kusto Query Language (KQL) query\n    query = \"AzureActivity | take 5\"\n\n    # Define the time interval for the query\n    end_time = datetime.now()\n    start_time = end_time - timedelta(hours=1)\n    time_interval = QueryTimeInterval(start_time=start_time, end_time=end_time)\n\n    print(f\"Executing query for workspace {workspace_id}...\")\n    response = client.query_workspace(\n        workspace_id=workspace_id,\n        query=query,\n        timespan=time_interval\n    )\n\n    for table in response.tables:\n        print(f\"\\nTable: {table.name}\")\n        print(\"-\" * len(f\"Table: {table.name}\"))\n        # Print columns (optional)\n        # for col in table.columns:\n        #     print(f\"  Column: {col.name} ({col.type})\")\n        \n        # Print rows\n        for row in table.rows:\n            print(f\"  Row: {row}\")\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\n    print(\"Ensure you have set up credentials (e.g., AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) \")\n    print(\"or authenticated via Azure CLI and have permissions to access the workspace.\")\n","lang":"python","description":"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."},"warnings":[{"fix":"Instead of `client.query_workspace(..., timespan=(start, end))`, use `from azure.monitor.query import QueryTimeInterval; time_interval = QueryTimeInterval(start_time=start, end_time=end); client.query_workspace(..., timespan=time_interval)` or pass a string like `timespan='PT1H'`.","message":"The `timespan` parameter for `LogsQueryClient.query_workspace` and `query_resource` methods changed from accepting raw `datetime` objects or `timedelta` to requiring a `QueryTimeInterval` object or a string. This is a significant change from v1.x.","severity":"breaking","affected_versions":"2.0.0 and later"},{"fix":"Update your code to directly iterate `response.tables` and `table.rows`. For example, `for table in response.tables: for row in table.rows: print(row)`.","message":"The response object structure for `LogsQueryClient.query_workspace` changed significantly in v2.0.0. Direct access to `response.tables` is now standard, simplifying iteration over results. In v1.x, often `.as_dict()` or different methods were needed to access the underlying data.","severity":"breaking","affected_versions":"2.0.0 and later"},{"fix":"Refer to the official Kusto Query Language documentation (learn.microsoft.com/azure/data-explorer/kusto/query/) for correct syntax and operators. Test your queries in the Azure portal's Log Analytics workspace before integrating into code.","message":"When querying logs, the query syntax uses Kusto Query Language (KQL), not SQL. Ensure your queries adhere to KQL syntax to avoid parsing errors. Incorrect KQL will result in query failures.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}