How do I use Logging in the Django Debug Toolbar?

送分小仙女□ 提交于 2019-12-03 06:30:21

问题


I would like to output debug messages in my django app at different points in a view function. The docs for the django-debug-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?


回答1:


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')



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2615042/how-do-i-use-logging-in-the-django-debug-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!