Home > Software design >  Log messages appearing twice - with and without formatting in Python Flask app
Log messages appearing twice - with and without formatting in Python Flask app

Time:11-05

I set up logging module wide like so:

def setup_logging(app):
    """
    Set up logging so as to include RequestId and relevant logging info
    """
    RequestID(app)
    handler = logging.StreamHandler()
    handler.setStream(sys.stdout)
    handler.propagate=False

    handler.setFormatter(
        logging.Formatter("[MHPM][%(module)s][%(funcName)s] %(levelname)s : %(request_id)s - %(message)s")
    )

    handler.addFilter(RequestIDLogFilter())  # << Add request id contextual filter
    logging.getLogger().addHandler(handler)
    logging.getLogger().setLevel(level="DEBUG")

and I use it so:

# in init.py
setup_logging(app)
# in MHPMService.py
logger = logging.getLogger(__name__)

But here's what I see on my console:

DEBUG:src.service.MHPMService:MHPMService.__init__(): initialized
[MHPM][MHPMService][__init__] DEBUG : 5106ec8e-9ffa-423d-9401-c34a92dcfa23 - MHPMService.__init__(): initialized

I only want the second type of logs in my application, how do I do this?

CodePudding user response:

I reset the handlers and got the expected behaviour:

logger.handlers=[]

CodePudding user response:

swap the current handlers

logging.getLogger().handlers[0] = handler

instead of doing this

logging.getLogger().addHandler(handler)
  • Related