I'm currently writing several Python modules which perform some I/O.
Thoses modules can be used directly by another developer or called trough a simple script I wrote, mainly for testing purposes.
I used the logging module and setup a StreamHandler to display logs on the standard error output and it works well. However I'm not sure how to make these logs customizable. Obviously I don't want to force those logs to be written on the standard output when a developer uses my classes. I'd like to give a choice, ideally to let him add his own handlers or none at all if he doesn't wants logs.
Are there any guidelines regarding Python logging for this case ? Should every class have its own logger ?
In short, how do you do it, and why ?
Thanks.
Make sure that modules intended to be used as libraries do not add any handlers (other than a NullHandler instance to the top-level logger of the library).
The best practice is to use loggers at module level, using
logger = logging.getLogger(__name__)
and, if necessary, using child loggers of this logger.
That way, your library log events map to the Python package hierarchy, and a user of your library modules can choose whether or not to use logging, and if using it, how to configure it with handlers.
It's OK to add handlers in things that are meant to be run as scripts.
It's OK to have convenience APIs to add handlers to your loggers, as long as your users can control whether to call those APIs.
There is a very good tutorial on the logging module for python
http://docs.python.org/howto/logging.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With