Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python best practice in terms of logging

Tags:

python

logging

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?

like image 988
Lucas Kauffman Avatar asked Apr 02 '14 10:04

Lucas Kauffman


People also ask

What are the five levels of logging in Python?

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.


1 Answers

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.

like image 53
Vinay Sajip Avatar answered Sep 20 '22 13:09

Vinay Sajip