[Solved]-How can exceptions in graphene-django be conditionally logged?


Try this. First ensure that intended exceptions are GraphQLError or descendants of it.

Then create a log filter like so:

import logging
from graphql import GraphQLError

class GraphQLLogFilter(logging.Filter):
    Filter GraphQL errors that are intentional.

    Any exceptions of type GraphQLError that are raised on purpose 
    to generate errors for GraphQL responses will be silenced from logs. 
    Other exceptions will be displayed so they can be tracked down.
    def filter(self, record):
        if record.exc_info:
            etype, _, _ = record.exc_info
            if etype == GraphQLError:
                return None
        if record.stack_info and 'GraphQLError' in record.stack_info:
            return None
        if record.msg and 'GraphQLError' in record.msg:
            return None

        return True

Use in your settings:

    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
    # Prevent graphql exception from displaying in console
    'filters': {
        'graphql_log_filter': {
            '()': GraphQLLogFilter,
    'loggers': {
        'graphql.execution.utils': {
            'level': 'WARNING',
            'handlers': ['console'],
            'filters': ['graphql_log_filter'],

Related resources:

Leave a comment