简体   繁体   中英

Configuring root logger in python

I have the following logging configuration in in my Django settings.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format':
              '%(levelname)s|%(asctime)s|%(name)s>> %(message)s',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        }
    },
    'loggers': {
         '': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': True,
         },
        'apps': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    }
}

With this configuration I expect my 'apps' to log at DEBUG level and any other modules to log only ERROR and above. But I see DEBUG messages from other modules. How do I fix it?

Are you using an empty string key in LOGGING['loggers'] to match the root logger? If so, you could try this instead.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format':
              '%(levelname)s|%(asctime)s|%(name)s>> %(message)s',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        }
    },
    'loggers': {
        'apps': {
            'handlers': ['console'],
            'level': 'DEBUG',
        }
    },
    'root': {
       'handlers': ['console'],
       'level': 'ERROR'
    }
}

I had a similar issue, with root logger configured a level at INFO but seeing DEBUG log message.

Turns out I should not set 'propagate': True for my other logger which is at level DEBUG , since that those logs will be passed to the root logger no matter what level root at.

So my guess here to the original question is that there might be some other modules' logger with propagate turned on. set disable_existing_loggers to True maybe solve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM