Registry / azure / azure-monitor-query

azure-monitor-query

JSON →
library2.0.0pypypi✓ verified 25d ago

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.

pip install azure-monitor-query azure-identity
INSTALL
IMPORT
SIG · AZURE-MONITOR-QUER
A
azure-monitor-query
azurepythonv2.0.0
Install
3.7s avg
Import
399ms
Disk
42MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.412s · 43.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.7s · import 0.386s · 44MB
42MB installed
● package 42MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

LogsQueryClient
from azure.monitor.query import LogsQueryClient
MetricsQueryClient
from azure.monitor.query import MetricsQueryClient
QueryTimeInterval
from azure.monitor.query import QueryTimeInterval
from datetime import datetime, timedelta # for timespan directly
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.
DefaultAzureCredential
from azure.identity import DefaultAzureCredential

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.")
Debug
Known issues
breakingThe `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.
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'`.
affects: 2.0.0 and later
breakingThe 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.
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)`.
affects: 2.0.0 and later
gotchaWhen 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.
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.
affects: All versions
Upgrade
Version history
2.0.0latest on PyPI · released Jul 30, 2025
Audit
Dependencies
azure-identityoptionalRequired for Azure Active Directory authentication, which is the recommended way to authenticate with Azure services.
Agent activity
26 hits · last 30 days
node
22
OpenAI (training)
1
Resources
azure-monitor-query — pip install azure-monitor-query · libregistry