Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to use a custom log formatter #381

Open
jackton1 opened this issue Jun 16, 2021 · 2 comments
Open

Unable to use a custom log formatter #381

jackton1 opened this issue Jun 16, 2021 · 2 comments

Comments

@jackton1
Copy link
Contributor

jackton1 commented Jun 16, 2021

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__(...)>"
@phillipuniverse
Copy link

I noticed this same issue. Any sort of timeline available for a fix?

@phillipuniverse
Copy link

I think the problem is in the emit:

def emit(self, record):

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
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants