raygun4py icon indicating copy to clipboard operation
raygun4py copied to clipboard

RaygunHandler fails when logging outside of an exception context.

Open jenstroeger opened this issue 4 years ago • 0 comments

Looking at the current Raygun logging handler:

https://github.com/MindscapeHQ/raygun4py/blob/f65727a8cc8c6e4b089a68efcd906d6dd7080568/python3/raygun4py/raygunprovider.py#L168-L178

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)

jenstroeger avatar Feb 10 '21 21:02 jenstroeger