First of all, I have read real python article on the subject.
Having learnt that loggers have a hierarchy, I want to create this new one called MyProjectLogger in such a hierarchy:
Root logger
· MyProjectLogger
· File logger 1
· File logger 2
· ... and so on with all the loggers in my project...
so that MyProjectLogger is used for all the descendant loggers, because right now I'm using all the same handlers with same configuration in all the loggers in my project (quite a lot). Although doing it through an only method, it doesn't feel right. In this way I would add the handlers only once to MyProjectLogger and all descendant loggers would just go up in the hierarchy using MyProjectLogger's handlers.
I don't want to use the default root logger for this because I have some third party libraries which are logging on it and right now I want the loggers in my project to log separately from the loggers in the libraries.
So, in summary:
- I want to define a logger MyProjectLogger in the hierarchy
- I want it to be direct descendant of root logger
- I want it to be the parent of all the loggers in my source code
- I believe I should use propagate=False so I can add the handlers to MyProjectLogger and getting it to handle of descendant loggers
My only doubt is: how do I give it such a name so that is under root and over the rest?
I know that:
logging.getLogger() # Gets the root logger
logging.getLogger(__name__) # Gets a logger for the present file
logging.getLogger(__package__) # Gets a logger for the present module
so let's say, if my project has this folder layout:
aaaBot/
main.py # Only file visible in this example.
# Please assume the rest of folders have files
common/
utils/
config/
database/
exceptions/
model/
wizards/
In every file for each folder I use logging.getLogger(__name__)
. __package__
in the root returns None and in the main executable main.py __name__
is '__main__'
.
Should I add a prefix + '.' for all the loggers in my project and create MyProjectLogger with that prefix (like getLogger(prefix+'.')
)?
If not, what should I do?