How to log messages _only once_ from all modules ?

Vinay Sajip vinay_sajip at yahoo.co.uk
Tue Nov 24 15:59:52 EST 2009


On Nov 24, 3:14 pm, Ron Barak <rbar... at gmail.com> wrote:
> Many thanks Soltys, that did the trick (actually, no need for setting
> propagate to 0), namely,
>
[snip]

It might work for now, but instantiating a handler in an instance
constructor can be an anti-pattern. If you ever create multiple client
instances, for example, you would create multiple handlers and add
those to the logger (which is essentially persistent for the lifetime
of the process), which could result in multiple messages, corrupted
output or exceptions (in the general case).

It's generally better to declare module-level loggers via

logger = logging.getLogger(__name__)

or, if better granularity is wanted, loggers with names prefixed by
__name__ + '.' - and handler set up should typically be done in one
place in such a way as to not inadvertently create handlers multiple
times. A common pattern is to just add handlers to the root logger
(e.g. the basicConfig() API does this) - other loggers automatically
get to use them, under normal circumstances.

Regards,

Vinay Sajip



More information about the Python-list mailing list