如何在 Graphene-Python 中记录异常

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

我目前的日志记录配置如下:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "default": {
            "format": "{levelname} {asctime} {process} {module}: {message}",
            "style": "{",
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "default",
        }
    },
    "loggers": {
        "server": {"handlers": ["console"], "level": "DEBUG"},
        "django": {"handlers": ["console"], "level": "INFO"},
        "graphql.execution.utils": {"handlers": ["console"], "level": "DEBUG"},
    },
}

但是,假设我在 schema.py 中做了类似的事情:

class Query(graphene.ObjectType):
    models = graphene.List(ModelType)

    def resolve_models(self, context):
        raise Exception("Test Exception")

异常返回给前端客户端。但是,没有迹象表明日志中发生了异常(与标准 Django 视图不同)。

如何配置 GraphQL,以便在 schema.py 中出现错误时使用 python / django 的日志记录功能?

python graphql graphene-python graphene-django
1个回答
0
投票

要捕获 GraphQL 解析器中发生的错误,您需要为 Graphene 设置自定义中间件。 Django 的日志配置无法直接了解 Graphene 执行流程中发生的情况,除非错误传播到中间件或更高层。

  • 设置中间件
# graphql_middleware.py
import logging

logger = logging.getLogger(__name__)

class LoggingErrorsMiddleware:
    def resolve(self, next, root, info, **args):
        try:
            return next(root, info, **args)
        except Exception as e:
            # Log the exception for our records
            logger.error("Error occurred in GraphQL execution:", exc_info=True)
            
            # Re-raise the exception so Graphene can handle it and convert it to a GraphQL error
            raise e
  • 将中间件添加到您的 GraphQL 设置中:
GRAPHENE = {
    ...
    'MIDDLEWARE': [
        'path.to.graphql_middleware.LoggingErrorsMiddleware',
    ],
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.