Python logging for custom namespace misses prefix

Viewed 19

I tried to enable logging for my python library. I want all logs to go into my custom subset my_logger instead of root. So this is what I tried:

import logging
my_logger = logging.getLogger('my_logger')
my_logger.warning("my hello!")
logging.warning("hello!")

And for some reason my custom logger didn't output subset name (my_logger) in front of it.

my hello!
WARNING:root:hello!

A simple change of the order of root and my loggers fixed the issue:

import logging
logging.warning("hello!")
my_logger = logging.getLogger('my_logger')
my_logger.warning("my hello!")

Output

WARNING:root:hello!
WARNING:my_logger:my hello!

I do not ever want to use a root logger at all. Is it possible to get WARNING:my_logger prefix to my output without logging to the root logger first?

1 Answers

Seems like the logging module is doing first-time configuration during the first call. You can do that first to get it out of the way before using your logger:

import logging

logging.basicConfig() # do the configuration
my_logger = logging.getLogger('my_logger')
my_logger.warning("my hello!")
logging.warning("hello!")

Result:

WARNING:my_logger:my hello!
WARNING:root:hello!

For a library that you expect others to import, this should be done by the code importing the module instead of the library.

Related