[Fixed]-Django log filter for slow SQL queries

9๐Ÿ‘

โœ…

So far, Iโ€™ve tried to use a CallbackFilter but I would prefer having a logging class.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'queries_above_300ms': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': lambda record: record.duration > 0.3 # output slow queries only
        },
    },
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "log", "logfile"),
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
            'filters': ['queries_above_300ms'],
        },
    },
    'loggers': {
        'django.db': {
            'handlers': ['logfile'],
            'level': 'DEBUG',
            'propagate': False,
        },
    }
}
๐Ÿ‘คBenjamin Toueg

3๐Ÿ‘

You can use a filter to attach the stack_info:

class SlowQueriesFilter(logging.Filter):
    """Filter slow queries and attach stack_info."""

    def filter(self, record):
        duration = record.duration
        if duration > 0.1:
            # Same as in _log for when stack_info=True is used.
            fn, lno, func, sinfo = logging.Logger.findCaller(None, True)
            record.stack_info = sinfo
            return True
        return False

Add it to your filters list and then use it with the logger:

LOGGING = {
    'filters': {
        'slow_queries': {
            '()': 'app.log_filters.SlowQueriesFilter',
        },
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'filters': ['slow_queries'],
        }
    }

Might require Python 3 for the stack_info handling, but a custom formatter
could also be used.

๐Ÿ‘คblueyed

Leave a comment