pyrollbar
pyrollbar copied to clipboard
Unable to use a custom log formatter
Formatter
...
'formatters': {
'custom': {
'format': '%(message)s %(my_object)r',
},
},
Handler
'handlers': {
'custom': {
'level': 'WARNING',
'class': 'rollbar.logger.RollbarHandler',
'formatter': 'custom',
},
},
Using:
log.warning('This is a test', extra={'my_object': my_object})
Expectation:
The correct formatted message shows up in rollbar.
currently shows
"This is a test"
Instead of
"This is a test <MyObject.__repr__(...)>"
I noticed this same issue. Any sort of timeline available for a fix?
I think the problem is in the emit: https://github.com/rollbar/pyrollbar/blob/f67253a67bc01b7ced2d55df1c1d37ac8224f0e9/rollbar/logger.py#L89
It is not taking into account the __dict__ of the LogRecord.
Here's how you could grab it out though:
DEFAULT_ATTRS = (
'args',
'asctime',
'created',
'exc_info',
'exc_text',
'filename',
'funcName',
'levelname',
'levelno',
'lineno',
'module',
'msecs',
'message',
'msg',
'name',
'pathname',
'process',
'processName',
'relativeCreated',
'stack_info',
'thread',
'threadName',
)
def get_extra_from_record(self, record):
"""
Returns the dict that was passed in as extra data
e.g. logging,info('Log log log', extra={'extra_code': 'ABC123'})
"""
return {
attr: record.__dict__[attr]
for attr in record.__dict__
if attr not in DEFAULT_ATTRS
}
You could extend from the RollbarHandler and use the information on get_extra_from_record to customize the message, maybe pass in as extra_data?
class RollbarWithExtraHandler(RollbarHandler):
def emit(self, record):
record.extra_data = self._get_extra_from_record(record)
super().emit(record)
def _get_extra_from_record(self, record):
"""
Returns the dict that was passed in as extra data
e.g. logging,info('Log log log', extra={'extra_code': 'ABC123'})
"""
return {
attr: record.__dict__[attr]
for attr in record.__dict__
if attr not in DEFAULT_ATTRS
}