How do I use Logging in the Django Debug Toolbar?

前端 未结 3 470
别跟我提以往
别跟我提以往 2021-02-02 06:09

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

相关标签:
3条回答
  • 2021-02-02 06:50

    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.

    0 讨论(0)
  • 2021-02-02 07:02

    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')
    
    0 讨论(0)
  • 2021-02-02 07:07

    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.

    0 讨论(0)
提交回复
热议问题