I'm definitely missing something when it comes to logging using the logging module. I can get it to work just fine if I have just 1 file with everything in it, but when I try to split things up into separate files or packages I'm not sure what to do.
Suppose I have a package with the following directory tree:
mypackage/
├─ __init__.py
├─ utils.py
├─ my_logger.py
main.py
In my package I have a logger (in my_logger.py) that is configured nearly to my liking. In my main.py file, I initialize that logger and add a FileHandler to start writing to a file.
However, I'd also like to log to this file from other files in my package. Say, for example, the file utils.py. How do I make the instance of logger in utils.py know about the FileHandler?
Suppose I have a series of functions in utils.py, say, myfunc1() and myfunc2(), and I'd like each to also log to the same file. I don't want to have to pass my instance of logger to each individual function.
There feels like an obvious setting I am missing. What should I have in which file in order to make sure they all know about the same logger instance everywhere in the package?
(A detail that may or may not be relevant — I've actually subclassed Logger to give it some custom behaviour. But this shouldn't affect the answer to this question, I don't think.)
getLogger(__name__)and if you want specific functions for logging when executing your main program, that's the only location where the custom configurations be used (e.g. attaching a handler to log to specific file(s)). Another thread describing another similar setup.getLogger(__name__)(note that's the only setup command, so they won't have handlers set up to write to their own files), they should leave it to the main program to set it up. It would be easier for you to actually try it out and see the results yourself.__name__of the module, e.g. callinggetLogger(__name__)insidemypackage/utils.pyshould return a logger named'mypackage.utils', and logs will be written to it. In your main application you should get the root logger just bygetLogger()and attach handlers to it, which will capture all the subloggers. If you want to only deal with messages in your package, simplygetLogger('mypackage')which will capture all loggers underneath'mypackage.*', which includesmypackage.utils.getLogger('a') == getLogger('a')isTrue. Logging to a logger returned bygetLogger('a.b')will show up for handlers attached togetLogger('a').