Making logging.getLogger() simpler

Vinay Sajip vinay_sajip at
Sun Sep 19 20:52:59 CEST 2010

On Sep 18, 5:35 pm, Lie Ryan <lie.1... at> wrote:
> I was expecting this to work:
>   importlogging
>   logger =logging.getLogger(__name__)
>   logger.warn('this is a warning')
> instead it produced the error:
>   No handlers could be found for logger "__main__"
> However, if instead I do:
>   importlogging
>  logging.warn('creating logger')
>   logger =logging.getLogger(__name__)
>   logger.warn('this is a warning')
> then it does work.
> Is there any reason why getLogger()-created logger shouldn't
> automatically create a default handler?

There is a good reason why a getLogger()-created logger doesn't add a
default handler. Imagine if it did, and the code you were writing was
a library module that was used in an application being written by
another developer. Imagine if there were several other libraries which
also declared loggers (and therefore several default handlers). Then
the result of running the application would be to get a whole bunch of
unexpected messages from those libraries, including yours. This would
annoy the application developer no end, and rightly so.

For simple uses of logging (where you are writing a utility script,
for example, when you are the application developer) you can call
logging.warning() etc. which will (for your convenience) add a handler
to write to the console for you, if there isn't a handler already.

If you are doing something more involved, you will need to configure
logging to do whatever it is you want, and when you run your program
your log will contain messages from your application as well as third-
party libraries you use, all playing well together and with no
unpleasant surprises.

If you are writing a library, you will typically:

1. Add a NullHandler to your top-level logger.
2. If you want to force your users (application developers) to add
handlers explicitly to their loggers, set your top-level logger's
propagate flag to False.
3. If you want to have a specific verbosity on your loggers, which is
different from the default (WARNING), you need to set that level on
your top-level logger, or on individual loggers for which you want
that specific, non-default verbosity.

I hope that helps,

Vinay Sajip

More information about the Python-list mailing list