简体   繁体   English

如何获取从 logging.Handler 传递给日志调用的实际 object

[英]How to get the actual object passed to a logging call from a logging.Handler

Suppose I do the following:假设我执行以下操作:

import logging

some_obj = MyObject()
logging.info(some_obj)

and I have a logging.Handler that handles this message:我有一个logging.Handler来处理这个消息:

class MyHandler(logging.Handler):

    def emit(self, record):
         # ...

Is there a way to get a reference to some_obj from my handler?有没有办法从我的处理程序中获取对some_obj的引用? From the documentation for logging.LogRecord , it would appear I can only get the string representation of the log invocation (ie the first argument merged with any formatting arguments to follow) through record.getMessage() .logging.LogRecord的文档中,看来我只能通过record.getMessage()

I'd like to do this so I can use properties/methods of the object to more cleanly handle logic in the handler.我想这样做,以便我可以使用 object 的属性/方法来更干净地处理处理程序中的逻辑。 Otherwise I have to base my handler logic on the contents of the string which will end up getting ugly very fast for this particular use case.否则,我必须将我的处理程序逻辑基于字符串的内容,对于这个特定的用例,这最终会变得非常难看。

Please let me know if there is any additional context required to answer this question.如果回答这个问题需要任何额外的上下文,请告诉我。 Thanks in advance.提前致谢。

The some_obj will be stored in the msg attribute of the LogRecord : this simple script some_obj将存储在LogRecordmsg属性中:这个简单的脚本

import logging

class MyClass(object):
    def __str__(self):
        return 'foo'

class MyHandler(logging.Handler):
    def emit(self, record):
        print('%r: %s' % (record.msg, record.msg))

logger = logging.getLogger()
logger.addHandler(MyHandler())
some_obj = MyClass()
logger.warning(some_obj)

should print something like this when it's run:运行时应该打印这样的内容:

<__main__.MyClass object at 0x0000000002934400>: foo <__main__.MyClass object at 0x0000000002934400>: foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM