Python protocol issues from multiple modules

I have 3 python modules.

LogManager.py Runner.py Other.py 

Runner.py is the first core module in the event chain, and from this module, a function is called inside Other.py .

So, inside Runner.py , I have a call to the LogManager.py function

 logger = LogManager.get_log() 

and from there I can make simple magazines, for example. logger.critical("OHNOES")

What I want to use get_log something similar to a singleton template, where if the log has not been configured, it will configure the logger and return it. In addition, it will simply return the registrar.

The contents of LogManager.py:

 import logging def get_log(): logger = logging.getLogger('PyPro') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('pypro.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # create formatter and add it to the handlers fhFormatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') chFormatter = logging.Formatter('%(levelname)s - %(filename)s - Line: %(lineno)d - %(message)s') fh.setFormatter(fhFormatter) ch.setFormatter(chFormatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) logger.info("-----------------------------------") logger.info("Log system successfully initialised") logger.info("-----------------------------------") return logger 

As you can see, LogManager.get_log () will try to configure the log every time it is called. Actually, I'm a little confused as to what is happening ...

Runner.py calls the get_log function in this main method. Other.py calls get_log in the global area (immediately after import, and not in any function)

As a result, all the logs I make are written twice, since the handlers are executed twice for the logger.

What is the easiest way that I'm missing to get get_log to return an instance of the same log?

+4
source share
1 answer

The logging module already implements a singleton template for you - when you call logger.getLogger(name) it will create a logger if it has not already done so and has not returned it. Although this is not quite what you are asking for, I would suggest simply renaming get_log() to setup_log() , as that is what it does. Then you can simply call setup_log() once, at the beginning of your code. Subsequently, when you really need a logger, just use logging.getLogger() and it will return the logger already configured.

+3
source

Source: https://habr.com/ru/post/911806/


All Articles