Skip to content

RaygunHandler fails when logging outside of an exception context. #98

@jenstroeger

Description

@jenstroeger

Looking at the current Raygun logging handler:

class RaygunHandler(logging.Handler):
def __init__(self, api_key, version=None):
logging.Handler.__init__(self)
self.sender = RaygunSender(api_key)
self.version = version
def emit(self, record):
userCustomData = {
"Logger Message": record.msg
}
self.sender.send_exception(userCustomData=userCustomData)

it calls send_exception() unconditionally, and that function expects to run within an exception context.

However, if I add the Raygun handler to my logging hierarchy then it’s likely to be invoked for non-exception contexts as well which causes the following exception:

  File "/usr/local/lib/python3.7/site-packages/some_package/some_file.py", line X, in some_function
    logger.error("Here be an error message")
  File "/usr/local/lib/python3.7/logging/__init__.py", line 1407, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/usr/local/lib/python3.7/logging/__init__.py", line 1514, in _log
    self.handle(record)
  File "/usr/local/lib/python3.7/logging/__init__.py", line 1524, in handle
    self.callHandlers(record)
  File "/usr/local/lib/python3.7/logging/__init__.py", line 1586, in callHandlers
    hdlr.handle(record)
  File "/usr/local/lib/python3.7/logging/__init__.py", line 894, in handle
    self.emit(record)
  File "/usr/local/lib/python3.7/site-packages/raygun4py/raygunprovider.py", line 178, in emit
    self.sender.send_exception(userCustomData=userCustomData)
  File "/usr/local/lib/python3.7/site-packages/raygun4py/raygunprovider.py", line 94, in send_exception
    errorMessage = raygunmsgs.RaygunErrorMessage(exc_type, exc_value, exc_traceback, options)
  File "/usr/local/lib/python3.7/site-packages/raygun4py/raygunmsgs.py", line 133, in __init__
    self.className = exc_type.__name__
AttributeError: 'NoneType' object has no attribute '__name__'

As per documentation, a Handler is expected to ignore messages below it’s current logging level (docs). Because there’s no dedicated “exception” level I think that in this case the Raygun handler should also ignore messages that don’t run in an exception context.

Thus, I’d like to propose the following change:

class RaygunHandler(logging.Handler):

    def emit(self, record):
        exc_type, _, _ = exc_info = sys.exc_info()
        if exc_type is not None:
            userCustomData = {
                "Logger Message": record.msg
            }
            self.sender.send_exception(exc_info=exc_info, userCustomData=userCustomData)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions