I am trying to get the logs from the log analytics workspace in Azure. While trying to access the workspace using Python I was getting the PathNotFoundError as below.
monitor_resource_id = "/subscriptions/ec1e-4764-9ebf/resourceGroups/test_resource/providers/Microsoft.OperationalInsights/workspaces/test_workspace"
time_range = timedelta(days=7)
def authenticate():
return DefaultAzureCredential()
def query_logs():
credential = authenticate()
try:
logs_query_client = LogsQueryClient(credential)
end_time = datetime.utcnow()
start_time = end_time - time_range
query = f"{log_query} | where TimeGenerated >= datetime({start_time.strftime('%Y-%m-%dT%H:%M:%SZ')}) and TimeGenerated <= datetime({end_time.strftime('%Y-%m-%dT%H:%M:%SZ')})"
timespan = (start_time, end_time)
response = logs_query_client.query_workspace(monitor_resource_id, query, timespan=timespan)
for table in response.tables:
for row in table.rows:
print(row)
except HttpResponseError as e:
print(f"HTTP Response Error: {e.message}")
print(f"Response status code: {e.status_code}")
print(f"Error details: {e.error}")
except Exception as e:
print(f"An error occurred: {e}")
HTTP Response Error: (PathNotFoundError) The requested path does not exist
Code: PathNotFoundError
Message: The requested path does not exist
Response status code: 404
Error details: (PathNotFoundError) The requested path does not exist
Code: PathNotFoundError
Message: The requested path does not exist
You can use my code
below to get the logs from Log Analytics (Modified a code a little code) and followed Microsoft-Document:
from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient
from datetime import datetime, timedelta
rithwik_workspace_id = "3c62e221"
rithwik_log_query = "AzureMetrics"
time_range = timedelta(days=7)
def authenticate():
return DefaultAzureCredential()
def rith_func():
creds = authenticate()
rithwik_client = LogsQueryClient(creds)
end_time = datetime.utcnow()
start_time = end_time - time_range
rithwik_query = f"{rithwik_log_query} | where TimeGenerated >= datetime({start_time.strftime('%Y-%m-%dT%H:%M:%SZ')}) and TimeGenerated <= datetime({end_time.strftime('%Y-%m-%dT%H:%M:%SZ')})"
tim = (start_time, end_time)
response = rithwik_client.query_workspace( rithwik_workspace_id, rithwik_query, timespan=tim)
for table in response.tables:
for row in table.rows:
print(row)
rith_func()
Output:
Here workspace id is not resource id . To get workspace id open your Log analytics workspace and then copy the id as below and use it: