Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the guidelines to allow customizable logging from a Python module? [closed]

Tags:

python

logging

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.

like image 599
ereOn Avatar asked Jun 13 '12 12:06

ereOn


2 Answers

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.

like image 180
Vinay Sajip Avatar answered Oct 20 '22 20:10

Vinay Sajip


There is a very good tutorial on the logging module for python

http://docs.python.org/howto/logging.html

like image 27
Simon Peverett Avatar answered Oct 20 '22 20:10

Simon Peverett