How do I use Logging in the Django Debug Toolbar?
I would like to output debug messages in my django app at different points in a view function. The docs for the django-deb开发者_JS百科ug-toolbar say it uses the build in python logging but I can't find any more information then that. I don't really want to log to a file but to the info pane on the toolbar. How does this work?
You just use the logging module methods and DjDT will intercept and display them in the Logging Panel.
import logging
logging.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 logging
logger = 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 below
LOGGING = {
# 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.
精彩评论