#StackBounty: #python #logging Change logger class of external packages

Bounty: 50

I want to use my own logger class to for all logger instances, the goal is to have consistent text formatting and easily save all records in the same file.

But I’m using a library that create a logger instance when I import it, then log messages when I run my code.

The solution seems to use setLoggerClass but it have to be called before the import stage. Which gives me:

import logging
from utils.logger import MyLogger

logging.setLoggerClass(MyLogger)

import other.packages

# Remove the handlers set on the external logger and replace by mine.
for handler in external_logger.handlers[:]:
    external_logger.removeHandler(handler)
external_logger.setup_my_handlers()

# Some code

This is working but looks dirty and doesn’t satisfy PEP8 code style guide line. I’m also afraid to break it after any refractory.

Is there any clean way to do this?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.