How do I use Logging in the Django Debug Toolbar?

前端 未结 3 511
别跟我提以往
别跟我提以往 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.

提交回复
热议问题