尝试访问日志分析工作区时出现路径错误

问题描述 投票:0回答:1

我正在尝试从 Azure 中的日志分析工作区获取日志。在尝试使用 Python 访问工作区时,我收到如下 PathNotFoundError。

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
python azure azure-api-management azure-log-analytics azure-api-apps
1个回答
0
投票

您可以使用我下面的

code
从Log Analytics获取日志(修改了一点代码)并按照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:

enter image description here

这里的工作空间 id 不是资源 id 。要获取工作区 ID,请打开您的日志分析工作区,然后复制如下 ID 并使用它:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.