0

我正在通过 Logging 适配器为 django Web 应用程序实现日志记录。我在每条日志消息之前发送一个自定义前缀,即“user@xyz.com”,以识别登录的用户。我已将 loggingAdapter 设置为单例,就像我注销应用程序时它只是删除会话但程序执行将仍然存在,下次我登录时,不应将用户前缀附加到现有前缀,因为 loggingadapter 对象仍未被破坏

logger=logging.getLogger("billingacct")#这在任何类之外,我从 settings.py 中获取“billingacct”值

    class LoggerAdapter(logging.LoggerAdapter):
      _instance=None
      def __new__(cls,logger,prefix):
        if cls._instance is None:
          print('Creating the object')
          cls._instance = super(LoggerAdapter, cls).__new__(cls)

          cls.prefix=prefix
                # Put any initialization here.
          return cls._instance
        else:
          print('Object already exists')
          cls.prefix=prefix
          return cls._instance


    def process(self, msg, kwargs):
      return '[%s] %s' % (self.prefix, msg), kwargs

我在入门类中调用上述类

def login:
    global logger
    email=<value set>
    logger = LoggerAdapter(logger, email)

日志记录第一次工作正常,如果我立即注销并登录,我会收到此错误

**Object already exists** #this is from the console,below from django logs

[19/Mar/2021 10:59:16] ERROR [django.request:224] Internal Server Error: /login
Traceback (most recent call last):
  File 
billingacct/views.py", line 308, in login
logger.info("{} ".format(request.session['role']))


File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/__init__.py", line 1794, in info
    self.log(INFO, msg, *args, **kwargs)



File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/__init__.py", line 1830, in log
    if self.isEnabledFor(level):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/__init__.py", line 1838, in isEnabledFor
    return self.logger.isEnabledFor(level)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/__init__.py", line 1838, in isEnabledFor
    return self.logger.isEnabledFor(level)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/logging/__init__.py", line 1838, in isEnabledFor
    return self.logger.isEnabledFor(level)
  [Previous line repeated 958 more times]
RecursionError: maximum recursion depth exceeded

谁能告诉我如何解决这个问题?

谢谢

4

1 回答 1

0

感谢您发布您的问题!我有一个类似的问题,与 django 无关。真是令人头疼,因为我只在重负载下看到了 RecursionError。在我的情况下,AWS Lambda 函数容器通常在我达到递归限制之前回收,但在重负载下......

发生的事情是您将记录器实例化为全局

logger=logging.getLogger("billingacct")

然后当你的函数第一次被调用时,全局被设置为一个日志适配器对象,里面有记录器。

def login:
    global logger
    email=<value set>
    logger = LoggerAdapter(logger, email)

在随后的调用中,适配器被嵌套在更多的适配器中,直到您达到递归深度限制。

您想在执行此操作之前检查全局的类型,如果是记录器,则将其放入适配器中,如果是适配器,则获取其记录器对象并将其放入新的适配器中。

def login:
    global logger
    email=<value set>
    if isinstance(logger, logging.Logger):
        logger = LoggerAdapter(logger, email)
    elif isinstance(logger, LoggerAdapter):
        logger = LoggerAdapter(logger.logger, email)
    
于 2021-09-02T09:04:30.493 回答