Search code examples
pythonazure-functionsazure-application-insights

How to get the Exception (Message and StackStrace) of a Python Azure Function


With the following AzureFunction (config.nonsense is not defined):

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

I produce the following Error (Shown here is the Monitoring LogStream):

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)

I cannot figure our how to get the full Stacktrace and ErrorMessage of this Exception in Application Insights. Here is my host.json :

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

Edit 1 zsbiconfig.py

import os
# from azure.identity import DefaultAzureCredential
# from azure.keyvault.secrets import SecretClient

class MyConfig:

    def __init__(self, ftp_host=None, ftp_username=None, ftp_password=None,
                 sharepoint_url=None, sharepoint_clientid=None, sharepoint_clientsecret=None, azure=False):

        self._ftp_host = ftp_host
        self._ftp_username = ftp_username
        self._ftp_password = ftp_password
        self._sharepoint_url = sharepoint_url
        self._sharepoint_clientid = sharepoint_clientid
        self._sharepoint_clientsecret = sharepoint_clientsecret

        self._azure = azure

        self._env_ftp_host = os.getenv('FTP_HOST')
        self._env_ftp_username = os.getenv('FTP_USERNAME')
        self._env_ftp_password = os.getenv('FTP_PASSWORD')
        self._env_sharepoint_url = os.getenv('SHAREPOINT_URL')
        self._env_sharepoint_clientid = os.getenv('SHAREPOINT_CLIENTID')
        self._env_sharepoint_clientsecret = os.getenv('SHAREPOINT_CLIENTSECRET')

        return

Solution

  • I have created a http trigger function and have used try-catch to log the exception message in application insight.

    You can also refer to this blog to know more about logging exception message and stack trace.

    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
            )
    

    You can see the detailed error message as shown below or you can also check them in invocation logs.

    enter image description here

    Invocation logs :-

    enter image description here

    Application insight logs :-

    enter image description here