No handlers could be found for logger

Viewed 104173

I am newbie to python. I was trying logging in python and I came across No handlers could be found for logger error while trying to print some warning through logger instance. Below is the code I tried

import logging
logger=logging.getLogger('logger')
logger.warning('The system may break down')

And I get this error No handlers could be found for logger "logger"

What's confusing me is when I first try to print warning using logging and then through logger , it works fine, like

>>> import logging
>>> logging.warning('This is a WARNING!!!!')
WARNING:root:This is a WARNING!!!!
>>> 
>>> logger.warning('WARNING!!!!')
WARNING:logger:WARNING!!!!

Can someone throw some light on what's happening in second scenario?

6 Answers

If you get this error when using sentry (No handlers could be found for logger "sentry.errors"), it could be due to sentry bug for SNI support.

check https://github.com/getsentry/raven-python/issues/523 for more details. a quick workaround is to replace DSN scheme by threaded+requests+https:

RAVEN_CONFIG = {
    'dsn': 'threaded+requests+https://xxxxxxxxxxxx@sentry.example.com/1',
}

For sake of completeness:

In order to make this work on a module level which might be used elsewhere or standalone you could do

logger = logging.getLogger(__name__)

# create own logging handler if nobody changed the root logger.
if not logging.root.handlers and not logger.handlers:
    handler = logging.StreamHandler()
    handler.formatter = logging.Formatter('%(asctime)s %(funcName)s %(levelname)s: %(message)s')
    logger.addHandler(handler)

This allows running the module standalone and avoids conflicts if it is used in a context which already configures the root logger.

Note that the error message described in the post only appears in Python 2. Python 3 prints the message to stdout if no handlers are defined in the hierarchy.

Related