Search code examples
pythonpython-2.7loggingpython-logging

Python2.7: How to create a new StreamHandler without losing the module name on each output line?


I want to replace the default StreamHandler, to redirect output to a different stream. However, when I create a new StreamHandler, the module name no longer appears in logging output:

import logging

logging.basicConfig(level = logging.INFO)

LOG = logging.getLogger(__name__)


for handler in logging.getLogger().handlers:
    logging.getLogger().removeHandler(handler)
logging.getLogger().addHandler(logging.StreamHandler())

# without the above 3 lines:  INFO:__main__:hello
# with   the above 3 lines:  hello


LOG.info('hello')

Is it possible to create a new StreamHandler without losing the module name on each output line?


Solution

  • Copy the formatter from the old handler to the new one:

    h, = logging.getLogger().handlers
    logging.getLogger().removeHandler(h)
    logging.getLogger().addHandler(logging.StreamHandler())
    logging.getLogger().handlers[0].setFormatter(h.formatter)