Odd behavior with imp.reload and logging

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 22 06:22:39 CEST 2011

On Wed, 21 Sep 2011 20:53:04 -0500, Andrew Berg wrote:

> When using a logger in a module and then using imp.reload to reload the
> module, logger messages are repeated in direct proportion to the number
> of times the modules was loaded. That is, on the first import, the
> message is written once, but on the second run, each message is written
> twice, three times on the third run, and so on.
> What causes this, and how can I fix it (or at least work around it)? Due
> to the nature of the program, it's much more convenient to reload a
> module than to restart the entire program (especially when testing).

You unconditionally add a handler every time you reload the module, 
regardless of whether or not the old handler is still there. You could 
try something like this (untested):

import logging
test_logger = logging.getLogger(__name__)
if not test_logger.handlers:
    console_handler = logging.StreamHandler()
    console_formatter = logging.Formatter(
       '{asctime} - {module} - {funcName} - line {lineno} - ' 
       '{levelname} - {message}', style='{'

test_logger.info('Test info')


More information about the Python-list mailing list