1

我正在使用 Docker 在计算引擎上运行 Django。我想知道当应用程序遇到像云运行这样的错误时,如何检查错误报告中的错误。

我正在研究如何在 Python 中设置错误报告。https://github.com/googleapis/python-error-reporting/tree/main/samples/snippets/fluent_on_compute

查看此示例,我似乎需要引发异常并运行report (traceback.format_exc ())以使用错误报告。

示例代码

def simulate_error():
    fluent.sender.setup('myapp', host='localhost', port=24224)

    def report(ex):
        data = {}
        data['message'] = '{0}'.format(ex)
        data['serviceContext'] = {'service': 'myapp'}
        # ... add more metadata
        fluent.event.Event('errors', data)

    # report exception data using:
    try:
        # simulate calling a method that's not defined
        raise NameError
    except Exception:
        report(traceback.format_exc())

当我运行 Django 时,除了使用try: execpt.

如何在错误报告中显示此类错误?

请让我知道是否有任何好的方法。谢谢你。

4

1 回答 1

0

Django 提供了一个选项来定义自定义异常处理程序
您可以定义自定义异常处理程序,如下所示,

from google.cloud import error_reporting
from rest_framework.views import exception_handler

# Initialize Error reporting client
client = error_reporting.Client()

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Send error to Error Reporting
    client.report(response)

    return response

在您的设置文件中添加以下配置,

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

要安装谷歌云错误报告库,请使用以下命令

pip install google-cloud-error-reporting

有关在 python 中设置错误报告的参考,请参阅

于 2021-11-26T15:22:28.093 回答