Several of these answers suggest that at the top of a module you you do
import logging
logger = logging.getLogger(__name__)
It is my understanding that this is considered very bad practice. The reason is that the file config will disable all existing loggers by default. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logger.info('Hi, foo')
class Bar(object):
def bar(self):
logger.info('Hi, bar')
And in your main module :
#main
import logging
# load my module - this now configures the logger
import my_module
# This will now disable the logger in my module by default, [see the docs][1]
logging.config.fileConfig('logging.ini')
my_module.foo()
bar = my_module.Bar()
bar.bar()
Now the log specified in logging.ini will be empty, as the existing logger was disabled by fileconfig call.
While is is certainly possible to get around this (disable_existing_Loggers=False), realistically many clients of your library will not know about this behavior, and will not receive your logs. Make it easy for your clients by always calling logging.getLogger locally. Hat Tip : I learned about this behavior from Victor Lin's Website.
So good practice is instead to always call logging.getLogger locally. E.g.
#my_module
import logging
logger = logging.getLogger(__name__)
def foo():
logging.getLogger(__name__).info('Hi, foo')
class Bar(object):
def bar(self):
logging.getLogger(__name__).info('Hi, bar')
Also, if you use fileconfig in your main, set disable_existing_loggers=False, just in case your library designers use module level logger instances.
fileConfig
in every module that does logging, unless you haveif __name__ == '__main__'
logic in all of them. prost's answer is not good practice if the package is a library, though it might work for you - one should not configure logging in library packages, other than to add aNullHandler
. – Vinay Sajippackage/__init__.py
. That's not normally the place you putif __name__ == '__main__'
code. Also, prost's example looks like it will call the config code unconditionally on import, which doesn't look right to me. Generally, logging config code should be done in one place and should not happen as a side-effect of import except when you're importing __main__. – Vinay Sajipif __name__ == '__main__'
? (it is not mentioned explicitly in question if this is the case) – kon psych