When using the logging
module from python for logging purposes. Is it best-practice to define a logger for each class?
Considering some things would be redundant such as file log location, I was thinking of abstracting logging to its own class and import an instance into each of my classes requiring logging. However I'm not sure if this is best practice or not?
In Python, the built-in logging module can be used to log events. Log messages can have 5 levels - DEBUG, INGO, WARNING, ERROR and CRITICAL. They can also include traceback information for exceptions. Logs can be especially useful in case of errors to help identify their cause.
Best practice is to follow Python's rules for software (de)composition - the module is the unit of Python software, not the class. Hence, the recommended approach is to use
logger = logging.getLogger(__name__)
in each module, and to configure logging (using basicConfig()
or dictConfig()
) from the main script.
Loggers are singletons - there is no point in passing them around or storing them in instances of your classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With