Reputation: 3494
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 (i.e. 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.
Upvotes: 0
Views: 83
Reputation: 99345
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
Upvotes: 1