我想在lambda函数中的所有python模块生成的日志前添加一个字符串。
假设有2个模块
a.py
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def dummymeth():
logger.info("hello world")
b.py
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def dummymeth2():
logger.info("hello world2")
...
我想在每个日志之前附加一个字符串,例如{tid = 123456789987654321 uid = 123456765432}。并且要附加的此字符串应该是可配置的。我尝试创建一个单例日志记录工厂,但是事情没有按预期进行。
答案 0 :(得分:1)
您可以创建一个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")