Search code examples
pythonflaskexceptionazure-application-insights

Get the exception easily with Azure app insight using python flask


I had tried the code below for getting the exception in https://learn.microsoft.com/en-us/azure/azure-monitor/app/opencensus-python


from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
logger.addHandler(AzureLogHandler(
    connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
)

properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}

# Use properties in exception logs
try:
    result = 1 / 0  # generate a ZeroDivisionError
except Exception:
    logger.exception('Captured an exception.', extra=properties)

It is working. I can catch the exception. However, I want to ask if there is an easy way to catch the exception automatically in the python flask? Since I try the below code, it just gives me a request record, not the exception.

        app = Flask(__name__)
        app.logger.addHandler(file_handler)
        handler = AzureEventHandler(
            connection_string="InstrumentationKey={}".format(app.config['APPINSIGHTS_INSTRUMENTATIONKEY']))
        handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))
        handler.setLevel(logging.ERROR)
        app.logger.addHandler(handler)

Thank you for helping


Solution

  • Your code should like below. For more details, you can check offical sample code.

    Flask "To-Do" Sample Application

    import logging
    import sys
    
    from flask import Flask
    
    sys.path.append('..')
    from config import Config
    from flask_sqlalchemy import SQLAlchemy
    from opencensus.ext.azure import metrics_exporter
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    from opencensus.ext.flask.flask_middleware import FlaskMiddleware
    from opencensus.trace import config_integration
    
    logger = logging.getLogger(__name__)
    app = Flask(__name__)
    app.config.from_object(Config)
    
    db = SQLAlchemy(app)
    
    # Import here to avoid circular imports
    from app import routes  # noqa isort:skip
    
    # Trace integrations for sqlalchemy library
    config_integration.trace_integrations(['sqlalchemy'])
    
    # Trace integrations for requests library
    config_integration.trace_integrations(['requests'])
    
    # FlaskMiddleware will track requests for the Flask application and send
    # request/dependency telemetry to Azure Monitor
    middleware = FlaskMiddleware(app)
    
    # Processor function for changing the role name of the app
    def callback_function(envelope):
        envelope.tags['ai.cloud.role'] = "To-Do App"
        return True
    
    # Adds the telemetry processor to the trace exporter
    middleware.exporter.add_telemetry_processor(callback_function)
    
    # Exporter for metrics, will send metrics data
    exporter = metrics_exporter.new_metrics_exporter(
        enable_standard_metrics=False,
        connection_string='InstrumentationKey=' + Config.INSTRUMENTATION_KEY)
    
    # Exporter for logs, will send logging data
    logger.addHandler(
        AzureLogHandler(
            connection_string='InstrumentationKey=' + Config.INSTRUMENTATION_KEY
            )
        )
    
    
    if __name__ == '__main__':
        app.run(host='localhost', port=5000, threaded=True, debug=True)