简体   繁体   English

使用 python flask 应用洞察力轻松获取异常

[英]Get the exception easily with Azure app insight using python flask

I had tried the code below for getting the exception in https://docs.microsoft.com/en-us/azure/azure-monitor/app/opencensus-python我试过下面的代码来获取https://docs.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?但是,我想问一下是否有一种简单的方法可以在 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感谢您的帮助

Your code should like below.您的代码应如下所示。 For more details, you can check offical sample code.有关更多详细信息,您可以查看官方示例代码。

Flask "To-Do" Sample Application Flask“待办事项”示例应用程序

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自定义异常未在 Python Flask 应用程序中捕获 - Custom Exception not caught in Python Flask App 有没有办法轻松地将数据从 python/flask 应用程序传递到 node.js 应用程序? - Is there a way to easily communicate data from a python/flask app to a node.js app? Azure 为函数应用程序使用 python Flask 框架 - Azure use python flask framework for function app Azure Python flask App - AD身份验证问题 - Azure Python flask App - AD authentication issue Python Flask:如何解决“应用程序中的错误:/ [GET]异常”? - Python Flask: How do I get around 'ERROR in app: Exception on / [GET]'? 从 html 中的 python 文件中获取信息 [使用烧瓶的 web 应用程序] - Get information from python file in html [web app using flask] Python flask @app.errorhandler(Exception) 得到完整的错误,而不仅仅是描述 - Python flask @app.errorhandler(Exception) get full error not just description 在Azure上部署Python Flask出现错误500 - Deploying Python Flask on Azure Get error 500 Python Flask 应用程序错误:'function' object 没有使用 Flask-Dance 的属性 'get' - Python Flask App Error: 'function' object has no attribute 'get' using Flask-Dance 编写一个代码,使用 python Flask 连接和读取 azure web 应用程序上已安装的存储? - Write a code that connects and reads the mounted storage on a azure web app using python flask?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM