Making logging.getLogger() simpler
Kev Dwyer
kevin.p.dwyer at gmail.com
Sun Sep 19 12:35:10 EDT 2010
On Sun, 19 Sep 2010 02:35:15 +1000, Lie Ryan wrote:
> I was expecting this to work:
>
> import logging
> 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:
>
> import logging
> 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?
Hello Lie,
Calling logging.warn(), or logging.debug() etc. before handlers
have been assigned to the root logger will result in
logging.basicConfig() being called automatically. By default a
StreamHandler will be created on the root logger and your logger
inherits the StreamHandler. So you can avoid the "No handlers..."
warning by calling logging.basicConfig() before your program
does any logging.
I don't know why getLogger() doesn't so something similar when
it's called. Perhaps so that the logger is explicitly
initialised with basic, file or dictConfig?
Cheers,
Kev
More information about the Python-list
mailing list