Azure Monitor Query
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
- breaking 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.
- breaking 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.
- gotcha 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.
Install
-
pip install azure-monitor-query azure-identity
Imports
- LogsQueryClient
from azure.monitor.query import LogsQueryClient
- MetricsQueryClient
from azure.monitor.query import MetricsQueryClient
- QueryTimeInterval
from azure.monitor.query import QueryTimeInterval
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
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.")