Search code examples
pythonazureazure-application-insightsazure-sdkazure-python-sdk

"Requested Path Does Not Exist" when trying to consult Log Analytics Workspace table


I'm doing a lab in which I use Azure Python SDK to create a resource group that contains: aks cluster, log analytics workspace and application insights (workspace-based). Then I run another service that creates an Availability Test for it. The third step would be to consult the "AppAvailabilityResults" table in the logs of the Workspace using a Flask app that has a route in which it makes a GET request for it. Everything up until this last step works, and I've debugged it so I know the credentials/LA infos are getting through my code correctly, but I get this error when I run the request:

raise HttpResponseError(message=error.message, response=error.response, model=model) azure.core.exceptions.HttpResponseError: (PathNotFoundError) The requested path does not exist Code: PathNotFoundError Message: The requested path does not exist INFO:werkzeug:127.0.0.1 - - [14/Sep/2023 14:34:02] "GET /checks HTTP/1.1" 500 -

This is how the code looks:

# Check Log Analytics and return results
def query_availability_results():
    try:
        query_client = LogsQueryClient(credentials)

        query = """
        AppAvailabilityResults
        """

        # Use timespan in query
        response = query_client.query_workspace(workspace_id=LOG_ANALYTICS_WORKSPACE.id, query=query, timespan=timespan)
        result_tables = LogsQueryResult.tables(response)

        return result_tables

    except Exception as e:
        app.logger.error(f"Error querying Log Analytics: {str(e)}")
        return None

# API route to check uptime
@app.route("/checks")
def get_checks():
    app.logger.info("Received request for /checks")
    # Execute the query and handle errors
    availability_results = query_availability_results()

    if availability_results is None:
        return jsonify({"error": "Error querying Log Analytics"}), 500

    checks = []
    try:
        for row in availability_results[0]:
            check = {
                "timeGenerated": row.get("timeGenerated", ""),
                "name": row.get("name", ""),
                "duration": row.get("durationMs", ""),
                "success": row.get("success", ""),
                "location": row.get("location", ""),
            }
            checks.append(check)
    except Exception as e:
        app.logger.error(f"Error parsing Log Analytics results: {str(e)}")
        return jsonify({"error": "Error parsing Log Analytics results"}), 500

    return jsonify(checks)

Any ideas? Thanks in advance.


Solution

  • The requested path does not exist," typically indicates that the query you're trying to execute against the Log Analytics Workspace is not finding the specified table or data source in the workspace.

    • Used this below code from this MSDOC in a flask app and able to trace the logs.
    app = Flask(__name__)
    
    # Configure logging to print logs to the console
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    
    # Define the LOG_WORKSPACE_ID as a string
    LOG_WORKSPACE_ID = " "
    
    credential = DefaultAzureCredential()
    client = LogsQueryClient(credential)
    
    @app.route('/')
    def query_and_print_logs():
        try:
            requests = [
                LogsBatchQuery(
                    query="     ",
                    timespan=timedelta(hours=1),
                    workspace_id=LOG_WORKSPACE_ID
                ),
                LogsBatchQuery(
                    query="  ",  # Replace with a valid log query
                    timespan=timedelta(days=1),
                    workspace_id=LOG_WORKSPACE_ID
                ),
                LogsBatchQuery(
                    query= """let Weight = 92233720368547758;
                    range x from 1 to 3 step 1
                    | summarize percentilesw(x, Weight * 100, 50)""",
                    workspace_id=LOG_WORKSPACE_ID,
                    timespan=(datetime(2021, 6, 2, tzinfo=timezone.utc), datetime(2021, 6, 5, tzinfo=timezone.utc)), # (start, end)
                    include_statistics=True
                ),
            ]
            results = client.query_batch(requests)
    
            for res in results:
                if res.status == LogsQueryStatus.FAILURE:
                    # this will be a LogsQueryError
                    logging.error(res.message)
                elif res.status == LogsQueryStatus.PARTIAL:
                    ## this will be a LogsQueryPartialResult
                    logging.warning(res.partial_error)
                    for table in res.partial_data:
                        df = pd.DataFrame(table.rows, columns=table.columns)
                        logging.info(df)
                elif res.status == LogsQueryStatus.SUCCESS:
                    ## this will be a LogsQueryResult
                    table = res.tables[0]
                    df = pd.DataFrame(table.rows, columns=table.columns)
                    logging.info(df.to_string())
    
            return "Check console logs for output."
    
        except Exception as e:
            logging.error(str(e))
            return "An error occurred. Check console logs for details."
    
    if __name__ == '__main__':
        app.run()
    

    Output:

    enter image description here

    enter image description here