How do I use Logging in the Django Debug Toolbar? How do I use Logging in the Django Debug Toolbar? django django

How do I use Logging in the Django Debug Toolbar?


You just use the logging module methods and DjDT will intercept and display them in the Logging Panel.

import logginglogging.debug('Debug Message')if some_error:   logging.error('Error Message')


Logging straight to the root logger, as @jonwd7 mentioned, is usually not recommended. Generally I'm following this pattern:

import logginglogger = logging.getLogger(__name__)del logging # To prevent accidentally using it...logger.debug("Some message")

This allows you to have much finer grained control over which logging messages do and don't show. Unfortunately, using it this way stops django debug toolbar from capturing any log messages unless you specify a particular logging configuration. Here's the simplest one I could come up with:

LOGGING = {    'version': 1,    'disable_existing_loggers': False,    'incremental': True,    'root': {        'level': 'DEBUG',    },}

Setting "incremental" and "disable_existing_loggers" are both important so you're not disabling the handler the toolbar attached to the root logger. All you're wanting to do is set the loglevel of the root logger to "DEBUG". You could also use the "loggers" entry to set levels for specific loggers. Just omit the "Handlers" section, and set "propagate":True so they're captured by the DjDT handler.


If you have an existing LOGGING config dict, and you don't want to mess it up by switching to 'incremental', you'll need to re-add the DjDT log as a handler, then add it to the root logger's list of handlers.

from debug_toolbar.panels.logging import collector # needed for handler constructor belowLOGGING = {    # existing options, formatters, loggers, etc    handlers = {        # existing handlers        'djdt_log': {            'level': 'DEBUG',            'class': 'debug_toolbar.panels.logging.ThreadTrackingHandler',            'collector': collector,        },    },    'root': {        'level': 'DEBUG',        'handlers': ['djdt_log'],    },}

If there's a cleaner way to do this, I'd love to see it.