Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging package - share log file between main and modules - python 3

My project is composed by a main.py main script and a module aaa.py . I've succesfully setup a log procedure by using the logging package in main.py, also specifying a log filename.

Which is the cleanest/"correct" way to let the functions contained in aaa.py to write in the same log file?

like image 932
user1403546 Avatar asked Dec 06 '25 08:12

user1403546


1 Answers

Use the root logger in main.py by defining

logger = logging.getLogger()
fh = logging.FileHandler("path/to/file")
logger.addHandler(fh)

Then use a module logger in aaa.py by defining

logger = logging.getLogger(__name__)

The logger does not have to have the same name as the module, but it is common practice. The submodule logger will automatically bubble up to the root logger and be sent to any handlers.

To quote from the docs

Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed.

like image 183
Chris Mueller Avatar answered Dec 08 '25 22:12

Chris Mueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!