Django Setup Default Logging

后端 未结 4 977
無奈伤痛
無奈伤痛 2020-12-04 05:40

I can\'t seem to figure out how to setup a \"default\" logger for my Django installation. I would like to use Django 1.3\'s new LOGGING setting in setting

4条回答
  •  醉梦人生
    2020-12-04 06:25

    I made a quick sample to check what configuration is used when both root key and the empty '' logger are referenced in config dict.

    import logging.config
    
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'fmt1': {
                'format': '[FMT1] %(asctime)-15s %(message)s',
            },
            'fmt2': {
                'format': '[FMT2] %(asctime)-15s %(message)s',
            }
        },
        'handlers': {
            'console1': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'fmt1',
            },
            'console2': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'fmt2',
            },
        },
        # First config for root logger: console1 -> fmt1
        'root': {
            'handlers': ['console1'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'loggers': {
            # Second config for root logger: console2 -> fmt2
            '': {
                'handlers': ['console2'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
    
    logging.config.dictConfig(LOGGING)
    
    l1 = logging.getLogger()
    l2 = logging.getLogger('')
    root = logging.root
    
    l1.info("l1")
    l2.info("l2")
    root.info("root logger")
    

    Prints the following result:

    [FMT1] 2018-12-18 17:24:47,691 l1
    [FMT1] 2018-12-18 17:24:47,691 l2
    [FMT1] 2018-12-18 17:24:47,691 root logger
    

    indicating that configuration under root key has the highest priority. If the block is removed, the result is:

    [FMT2] 2018-12-18 17:25:43,757 l1
    [FMT2] 2018-12-18 17:25:43,757 l2
    [FMT2] 2018-12-18 17:25:43,757 root logger
    

    In both case, I was able to debug and determine that all three loggers (l1, l2 and root) referenced the same logger instance, the root logger.

    Hope that will help others who, like me, were confused by the 2 different ways to configure the root logger.

提交回复
热议问题