How to Log Exceptions in Graphene-Python

How to Log Exceptions in Graphene-Python


0

I currently have my logging configured as follows:

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"},
    },
}

However, let’s say I do something like this in my schema.py:

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

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

The exception is returned to the front-end client. However, there is no indication that an exception occurred in the logs (unlike in standard Django views).

How do I configure GraphQL so it uses python / django’s logging capabilities when errors occur in schema.py?

1 Answer
1


0

To capture errors that occur within your GraphQL resolvers, you need to set up a custom middleware for Graphene. Django’s logging configuration is not directly aware of what happens inside Graphene’s execution flow unless errors propagate up to the middleware or higher layers.

  • Setup middleware
# 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
  • Add the middleware to your GraphQL settings:
GRAPHENE = {
    ...
    'MIDDLEWARE': [
        'path.to.graphql_middleware.LoggingErrorsMiddleware',
    ],
    ...
}

1

  • The errors are correctly printed using graphene 2, however. So why does it work for the previous version, but not graphene 3?

    – Langston Nashold

    13 mins ago



Leave a Reply

Your email address will not be published. Required fields are marked *