mardi 5 décembre 2017

Python Setup logging configuration only once

I want to read the logging.config file only once and enable/disable the logger only once for the all the modules in my python project. I tried the following ways: 1. Using @staticmethod 2. Using Singelton pattern. Which is the better way to initialize or setup the logging only once for the entire python project?

#Log.py
import logging.config
class Monitor(object):

    fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 
    logging.config.fileConfig(fileName)
    logger = logging.getLogger('root') 
    logger.disabled = True/False #set from some other config file

    @staticmethod
    def Log(logMessage):
        Monitor.logger.info(logMessage)

#Log1.py
class Monitor(object):

    # Here will be the instance stored.
    __instance = None

    def __init__(self):
        if Monitor.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            Monitor.__instance = self
            self.fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 
            logging.config.fileConfig(self.fileName)
            logger = logging.getLogger('root') 
            logger.disabled = True/False #set via some config file


    @staticmethod
    def Log(logMessage):
        if Monitor.__instance == None:
            Monitor.__instance = Monitor()
            Monitor.logger.info(logMessage)
        else:
            Monitor.logger.info(logMessage)

Aucun commentaire:

Enregistrer un commentaire