Wednesday, May 3, 2023

Python Root Logger and problems

Let’s look at the below code:


# 1. code inside myprojectmodule.py

import logging

logging.basicConfig(file='module.log')


#-----------------------------


# 2. code inside main.py (imports the code from myprojectmodule.py)

import logging

import myprojectmodule  # This runs the code in myprojectmodule.py


logging.basicConfig(file='main.log')  # No effect, because!

Imagine you have one or more modules in your project. And these modules use the basic root module. Then, when importing the module (‘myprojectmodule.py‘), all of that module’s code will run and logger gets configured.


Once configured, the root logger in the main file (that imported the ‘myprojectmodule‘ module) will no longer be able to change the root logger settings. Because, the logging.basicConfig() once set cannot be changed.


That means, if you want to log the messages from myprojectmodule to one file and the logs from the main module in another file, root logger can’t that.


references:

https://www.machinelearningplus.com/python/python-logging-guide/


No comments:

Post a Comment