我只想读一次logging.config文件,只为我的python项目中的所有模块启用/禁用一次记录器。我尝试了以下方法:1。使用@staticmethod 2.使用Singelton模式。对于整个python项目,只有一次初始化或设置日志记录的更好方法是什么?
#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)
答案 0 :(得分:0)
使用singelton模式进行设置
#log.py
import logging.config
import yaml
from singleton_decorator import singleton
@singleton
class Log:
def __init__(self):
configFile = 'path_to_my_lof_config_file'/logging.yaml
with open(configFile) as f:
config_dict = yaml.load(f)
logging.config.dictConfig(config_dict)
self.logger = logging.getLogger('root')
def info(self, message):
self.logger.info(message)
#module1.py
from Log import Log
myLog = Log()
myLog.info('Message logged successfully)
#module2.py
from Log import Log
myLog = Log() #config read only once and only one object is created
myLog.info('Message logged successfully)