【问题标题】:Appending a string to all the python logs aws lambda将字符串附加到所有 python 日志 aws lambda
【发布时间】:2019-07-28 22:45:49
【问题描述】:

我想在我的 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}。并且这个要附加的字符串应该是可配置的。我尝试创建一个单例日志工厂,但事情没有按预期工作。

【问题讨论】:

    标签: python-3.x logging aws-lambda python-logging


    【解决方案1】:

    您可以创建一个单例 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")
    

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 2020-06-17
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多