вы можете создать класс Singleton Python и войти в него отсюда.
ПРИМЕЧАНИЕ. Приведенный ниже код не будет работать в многопоточной среде.
import logging
class Singleton(type):
"""
Define an Instance operation that lets clients access its unique
instance.
"""
def __init__(cls, name, bases, attrs, **kwargs):
super().__init__(name, bases, attrs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class SingletonLogger(metaclass=Singleton):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
extra = None
context_string = "{}"
def setContext(self, extra={}):
self.extra = extra
self.context_string = self.get_mdc_like_String(extra)
def info(self, msg, *args, **kwargs):
self.logger.info(self.context_string + " " + msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
self.logger.error(self.context_string + " " + msg, *args, **kwargs)
def get_mdc_like_String(self, parameters):
message_context_array = []
for key, value in parameters.items():
# adding key=value since splunk will recognise it that way.
message_context_array.append(key + "=" + value)
return "{" + " ,".join(message_context_array) + "}"
Теперь в ваших модулях вы можете просто сделать
a.py
from src.util.Singleton_logger import SingletonLogger
from b import dummymeth2
logger = SingletonLogger()
logger.setContext({"a":"b", "c":"d"})
def dummymeth():
logger.info("hello world")
dummymeth2()
b.py
from src.util.Singleton_logger import SingletonLogger
logger = SingletonLogger()
def dummymeth2():
logger.info("hello world")