如何获取 Python Azure Function 的异常(Message 和 StackStrace)

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

使用以下AzureFunction(

config.nonsense
未定义):

import azure.functions as func
import logging
import zsbiconfig
# import triggerfunc

app = func.FunctionApp()

@app.timer_trigger(schedule="0 */1 * * * *", arg_name="myTimer", run_on_startup=True,
                   use_monitor=False)
def zsdbi(myTimer: func.TimerRequest) -> None:

    if myTimer.past_due:
        logging.info('The timer is past due!')

    logging.info('27 Python timer trigger function executed.')

    config = zsbiconfig.MyConfig(azure=True)
    print('config.ftp_host:', config.ftp_host)
    print('config.ftp_username:', config.ftp_username)
    print('config.ftp_password:', config.ftp_password)
    print('config.ftp_nonsense:', config.nonsense)         # I will produce a Exception

    # err = triggerfunc.triggerfunc(config)

    return

我产生以下错误(此处显示的是监控日志流):

2025-01-17T13:45:00Z   [Verbose]   Sending invocation id: 'f65a61af-e12a-4bfe-8bd2-7e30fee4eede
2025-01-17T13:45:00Z   [Verbose]   Posting invocation id:f65a61af-e12a-4bfe-8bd2-7e30fee4eede on workerId:3ec07702-7f0c-4a61-a0e7-57e542651161
2025-01-17T13:45:00Z   [Information]   27 Python timer trigger function executed.
2025-01-17T13:45:00Z   [Error]   Executed 'Functions.zsdbi' (Failed, Id=f65a61af-e12a-4bfe-8bd2-7e30fee4eede, Duration=9ms)

我无法弄清楚如何在 Application Insights 中获取此异常的完整 Stacktrace 和 ErrorMessage。这是我的 host.json :

  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

python azure-functions azure-application-insights
1个回答
0
投票

我创建了一个 http 触发函数,并使用 try-catch 在应用程序洞察中记录异常消息。

您还可以参考此博客以了解有关记录异常消息和堆栈跟踪的更多信息。

import azure.functions as func
import logging

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="http_trigger1")
def http_trigger1(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        name = req.params.get('name')
        if not name:
            req_body = req.get_json()  
            name = req_body.get('name')

        if not name:
            raise ValueError("The 'name' parameter is required either in the query string or in the request body.")
        
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")

    except Exception as e:
        logging.error("An error occurred while processing the request.", exc_info=True)
        return func.HttpResponse(
            f"An error occurred: {str(e)}",
            status_code=500
        )

您可以看到如下所示的详细错误消息,也可以在调用日志中查看它们。

enter image description here

调用日志:-

enter image description here

应用程序洞察日志:-

enter image description here

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