A Python application we're developing requires a logger. A coworker argues that the logger should be created and configured in every class that's using it. My opinion is that it should be created and configured on application start and passed as a constructor-parameter.
Both variants have their merits and we're unsure what the best practice is.
Not usually; it is typically not meant to be passed as a parameter.
The convention is to use
log = logging.getLogger(__name__)
in the top of each module. The value of__name__
is different for each module. The resultant value of__name__
can then be reflected in each log message.I think passing logger as parameter isn't good idea. You should consider a global logger as own module, it would be the best idea. For example:
logger.py
classFoo.py
classBar.py
Maybe this helps you to get an idea? Of course you can make it much better, reading settings from a config file or whatever but this is quick example.
A separate module to configure the logging:
mylogmod.py
:The
main.py
:A class
myclass.py
from a module with self test. You can do something similar in a unittest: (Note that you don't need to import the logging module in a unittest, just thestartlogging
function is enough. This way you can set the default level to warning or error and the unittests and self tests to debug)