简体   繁体   中英

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:

class MyHandler(logging.Handler):

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

Is there a way to get a reference to some_obj from my handler? 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() .

I'd like to do this so I can use properties/methods of the object to more cleanly handle logic in the handler. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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