Package: raygun4py
raygun4pyOfficial Raygun provider forPython 2.7,Python 3.1+andPyPyPython 2.7is supported in versions <= 4.4.0Please also refer to ourdocumentation site, as this is maintained with higher priority.InstallationThe easiest way to install this is as a pip package, as it is available from PyPI. From your command line, run:$ pip install raygun4pyTest the installationFrom the command line, run:$ raygun4py test your_apikeyReplaceyour_apikeywith the one listed on your Raygun dashboard. This will cause a test exception to be generated and sent.UsageImport and instantiate the module:fromraygun4pyimportraygunprovidersender=raygunprovider.RaygunSender("paste_your_api_key_here")Automatically send the current exception like this:try:raiseException("foo")except:sender.send_exception()Seesending functionsfor more ways to send.Uncaught exception handlerTo automatically send unhandled exceptions, you can provide a callback function tosys.excepthook:defhandle_exception(exc_type,exc_value,exc_traceback):sender=raygunprovider.RaygunSender("your_apikey")sender.send_exception(exc_info=(exc_type,exc_value,exc_traceback))sys.__excepthook__(exc_type,exc_value,exc_traceback)sys.excepthook=handle_exceptionNote that after sending the exception, we invoke the defaultsys.__excepthook__to maintain the expected behavior for unhandled exceptions. This ensures the program terminates as it would without the custom exception handler in place.LoggingYou can send errors/exceptions via a logger by attaching aRaygunHandler:logger=logging.getLogger()raygun_handler=raygunprovider.RaygunHandler("paste_your_api_key_here")logger.addHandler(raygun_handler)ARaygunHandlercan also be instantiated from an existingRaygunSender:raygun_handler=raygunprovider.RaygunHandler.from_sender(sender)It is then recommended to uselogger.exception()orlogger.error(exc_info=True)in the scope of anexceptblock:try:raiseException("Example exception")except:logger.exception("Example logger.exception log")# Orlogger.error("Example logger.error log",exc_info=True)Note that using aRaygunHandleroutside the scope of anexceptblock will not allow it to populate a full stack trace.Web frameworksRaygun4py includes dedicated middleware implementations for Django and Flask, as well as generic WSGI frameworks (Tornado, Bottle, Ginkgo etc). These are available for both Python 2.7 and Python 3.1+.DjangoTo configure Django to automatically send all exceptions that are raised in views to Raygun, add the following tosettings.py:MIDDLEWARE_CLASSES=('raygun4py.middleware.django.Provider')RAYGUN4PY_CONFIG={'api_key':'paste_your_api_key_here'}The above configuration is the minimal required setup. The full set of options supported by the provider can be declared in the same way:RAYGUN4PY_CONFIG={'api_key':'paste_your_api_key_here','http_timeout':10.0,'proxy':None,'before_send_callback':None,'grouping_key_callback':None,'filtered_keys':[],'ignored_exceptions':[],'transmit_global_variables':True,'transmit_local_variables':True,'enforce_payload_size_limit':True,'log_payload_size_limit_breaches':True,'transmit_environment_variables:':True,'userversion':"Not defined",'user':None}‘enforce_payload_size_limit’ when enabled (default behavior) will iteratively remove the largest global or local variable from the error message until the payload is below 128kb as payloads over 128kb will not be accepted by Raygun
‘log_payload_size_limit_breaches’ when enabled (default behavior) will log breaches and specify which variables are being removedFlaskTo attach a request exception handler that enhances reports with Flask-specific environment data, use our middlewareflask.Provider:fromflaskimportFlask,current_appfromraygun4py.middlewareimportflaskapp=Flask(__name__)flask.Provider(app,'your_apikey').attach()Theflask.Providerconstructor can also take an optionalconfigargument. This should be a standardDictof supported options, as shown in advanced configuration below. It also returns the underlyingRaygunSender, which you may decide to use elsewhere.WSGIAn example usingTornado, which will pick up exceptions that occur in the WSGI pipeline:fromraygun4py.middlewareimportwsgiclassMainHandler(tornado.web.RequestHandler):definitialize(self):raiseException('init')defmain():settings={'default_handler_class':MainHandler}application=tornado.web.Application([(r"/",MainHandler),],**settings)wsgiapp=tornado.wsgi.WSGIAdapter(application)raygun_wrapped_app=wsgi.Provider(wsgiapp,'your_apikey')server=wsgiref.simple_server.make_server('',8888,raygun_wrapped_app)server.serve_forever()Thewsgi.Providerconstructor can also take an optionalconfigargument. This should be a standardDictof supported options, as shown in advanced configuration below.Note that many frameworks (tornado, pryramid, gevent et al) will swallow exceptions that occur within their domain.Let us know if we’re missing middleware for your framework, or feel free to submit a pull request.Attaching raw HTTP request dataIf you are in a web server environment and have HTTP request details available, you can pass these and the headers through in a dictionary (seesample.py).Code running on Google App Engine should now be supported - you can test this locally, and has been reported working once deployed (the latter currently requires a paid account due to needed SSL support).DocumentationInitialization optionsRaygunSenderaccepts aconfigdict which is used to set options for the provider (the defaults are shown below):fromraygun4pyimportraygunproviderclient=raygunprovider.RaygunSender('your_apikey',config={'http_timeout':10.0,'proxy':None,'before_send_callback':None,'grouping_key_callback':None,'filtered_keys':[],'ignored_exceptions':[],'transmit_global_variables':True,'transmit_local_variables':True,'transmit_environment_variables:':True,'userversion':"Not defined",'user':None})For the local/global/environment variables, if their options are set to False the corresponding variables will not be sent with exception payloads.httpTimeout controls the maximum time the HTTP request can take when POSTing to the Raygun API, and is of type ‘float’.Sending functionsFunctionArgumentsTypesend_exceptionexceptionExceptionexc_info3-tupletagsListuserCustomDataDicthttpRequestDictAll parameters are optional.Call this function from within a catch block to send the current exception to Raygun:# Automatically gets the current exceptionhttpResult=client.send_exception()# Uses the supplied sys.exc_info() tuplehttpResult=client.send_exception(exc_info=sys.exc_info())# Uses a supplied Exception objecthttpResult=client.send_exception(exception=exception)# Send tags, custom data and an HTTP request objecthttpResult=client.send_exception(tags=[],userCustomData={},request={})You can pass ineitherof these two exception params:exceptionshould be a subclass of type Exception. Pass this in if you want to manually transmit an exception object to Raygun.exc_infoshould be the 3-tuple returned fromsys.exc_info(). Pass this tuple in if you wish to use it in other code aside from send_exception().send_exception also supports the following extra data parameters:tagsis a list of tags relating to the current context which you can define.userCustomDatais a dict containing custom key-values also of your choosing.httpRequestis HTTP Request data - seesample.pyfor the expected format of the object.Config and data functionsFunctionArgumentsTypefilter_keyskeysListIf you want to filter sensitive data out of the payload that is sent to Raygun, pass in a list of keys here. Any matching keys on the top level Raygun message object, or within dictionaries on the top level Raygun message object (including dictionaries nested within dictionaries) will have their value replaced with<filtered>- useful for passwords, credit card data etc. Supports * at the end of a key to indicate you want to filter any key that contains that key, ie foo_* will filter foo_bar, foo_qux, foo_baz etcFunctionArgumentsTypeignore_exceptionsexceptionsListProvide a list of exception types to ignore here. Any exceptions that are passed to send_exception that match a type in this list won’t be sent.FunctionArgumentsTypeon_before_sendcallbackFunctionYou can mutate the candidate payload by passing in a function that accepts one parameter using this function. This allows you to completely customize what data is sent, immediately before it happens.FunctionArgumentsTypeon_grouping_keycallbackFunctionPass a callback function to this method to configure custom grouping logic. The callback should take one parameter, an instance of RaygunMessage, and return a string between 1 and 100 characters in length (see ‘Custom Grouping Logic’ below for more details).FunctionArgumentsTypeset_proxyhostStringportIntegerCall this function if your code is behind a proxy and want Raygun4py to make the HTTP request to the Raygun endpoint through it.FunctionArgumentsTypeset_versionversionStringCall this to attach a SemVer version to each message that is sent. This will be visible on the dashboard and can be used to filter exceptions to a particular version, deployment tracking etc.FunctionArgumentsTypeset_useruser_infoDictCustomer data can be passed in which will be displayed in the Raygun web app. The dict you pass in should look this this:client.set_user({'firstName':'Foo','fullName':'Foo Bar','email':'foo@bar.com','isAnonymous':False,'identifier':'foo@bar.com'})identifiershould be whatever unique key you use to identify customers, for instance an email address. This will be used to create the count of affected customers. If you wish to anonymize it, you can generate and store a UUID or hash one or more of their unique login data fields, if available.Custom grouping logicYou can create custom exception grouping logic that overrides the automatic Raygun grouping by passing in a function that accepts one parameter using this function. The callback’s one parameter is an instance of RaygunMessage (python[2/3]/raygunmsgs.py), and the callback should return a string.The RaygunMessage instance contains all the error and state data that is about to be sent to the Raygun API. In your callback you can inspect this RaygunMessage, hash together the fields you want to group by, then return a string which is the grouping key.This string needs to be between 1 and 100 characters long. If the callback is not set or the string isn’t valid, the default automatic grouping will be used.By example:classMyClass(object):defmy_callback(self,raygun_message):returnraygun_message.get_error().message[:100]# Use naive message-based grouping onlydefcreate_raygun_and_bind_callback(self):sender=raygunprovider.RaygunSender('api_key')sender.on_grouping_key(self.my_callback)The RaygunSender above will use the my_callback to execute custom grouping logic when an exception is raised. The above logic will use the exception message only - you’ll want to use a more sophisticated approach, usually involving sanitizing or ignoring data.Chained exceptionsFor Python 3, chained exceptions are supported and automatically sent along with their traceback.This occurs when an exception is raised while handling another exception - see tests_functional.py for an example.ChangelogView the release history here