Documentation

Adobe Air

Documentation - RaygunAS - Adobe Air

Get Adobe Air error and crash reporting with Raygun. Adobe Air is supported using the third party provider RaygunAS.

RaygunAS is hosted on Github here: https://github.com/MindscapeHQ/raygunAS

Building the Client

Clone the repository and build the .swc file..

Copy the .swc file to wherever you have your libs and all is set.

Usage

Then go to your app and put the following lines in the main Sprite class, after some initial setup is complete, but before the main drawing begins:

_raygunAs = new RaygunAS(this,RAYGUN_API_KEY, APP_VERSION);
_raygunAs.addEventListener(RaygunAS.READY_TO_ZAP, onRaygunReady);
    _raygunAs.chargeRaygun();
}

private function onRaygunReady( event:Event ):void
{
    //do logic here
}

Initialize your main method in the onRaygunReady callback, this will allow RaygunAS to capture an error at any point in the stack.

That's that for the setup, and now if you create an Error RaygunAS will be triggered and send the Error report to your app's dashboard.

Additionally you can attach a RaygunAs.RAYGUN_COMPLETE listener to your RaygunAS instance in order to catch those error. It handles UncaughtErrorEvent.UNCAUGHT_ERROR events.

Android

Documentation - Raygun4Android - Android Crash Reporting

The Raygun4Android provider

Raygun4Android is a library that you can easily add to your Android app, which will then allow you to transmit all exceptions to your Raygun.io dashboard. Installation is painless, and configuring your site to transmit errors and crashes takes less than five minutes, so you can start receiving error and crash reports right away.

Raygun4Android supports all devices with Gingerbread and newer installed (2.3/API v9). It can be added as a Gradle or Maven dependency, or manually adding the JAR to your project (if you use Ant or other build tools).

Setup instructions

Gradle and Android Studio

Ensure Maven Central is present in your project's build.gradle:

allprojects {
    repositories {
        mavenCentral()
    }
}

Then add the following two compile statements to the dependencies section in your module's build.gradle:

dependencies {
    // Existing dependencies may go here
    compile 'com.google.code.gson:gson:2.1'
    compile 'com.mindscapehq.android:raygun4android:3.0.0'
}

Then sync your project. You may need to add the following specific imports to your class, where you wish to use RaygunClient:

import main.java.com.mindscapehq.android.raygun4android.RaygunClient;
import main.java.com.mindscapehq.android.raygun4android.messages.RaygunUserInfo;

Then see the configuration section below.

With Maven

To your pom.xml, add:

<dependency>
    <groupId>com.mindscapehq.android</groupId>
    <artifactId>raygun4android</artifactId>
    <version>[1.0.0,2.0.0)</version>
</dependency>

In your IDE, build your project (or run mvn compile), then see the configuration section below.

With Ant, other build tools, or manually

Download the JAR for the latest version, as well as the Gson library (if you do not already use it). Place both of these in a /lib folder in your project, add them to your project's classpath, then see below.

Configuration and Usage

  1. In your AndroidManifest.xml, make sure you have granted Internet permissions. Beneath the manifest element add:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  2. Inside the application element, add:

    <service   android:name="main.java.com.mindscapehq.android.raygun4android.RaygunPostService"
               android:exported="false"
               android:process=":raygunpostservice"/>
    <meta-data android:name="com.mindscapehq.android.raygun4android.apikey"
               android:value="PASTE_YOUR_API_KEY_HERE" />

    And replace the value in meta-data with your API key, available from your Raygun dashboard.

  3. In a central activity method (such as onCreate()), call the following:

    RaygunClient.init(getApplicationContext());
    RaygunClient.attachExceptionHandler();

    The above exception handler automatically catches & sends all uncaught exceptions. You can create your own or send from a catch block by calling RaygunClient.send() and passing in the Throwable.

A usage example is also available from the GitHub repository and Maven, in /sample-app.

ProGuard support

Raygun includes support for retracing your exception reports that have been obfuscated with ProGuard. This is achieved if you upload the relevant ProGuard mapping.txt file to your application in Raygun. Retracing is done automatically to each report as they come into Raygun so that they are presented to you with readable stacktraces.
All the documentation for ProGuard support can be found here.

Unique user tracking

Raygun supports tracking the unique users who encounter bugs in your apps. You can transmit the current user who was affected by the exception by calling setUser(string) and passing in their user name or email address. A count of affected users will then appear in the error statistics in Raygun. If you provide an email address, you will see it on the error page in Raygun, and if they have an associated Gravatar you will see that too. If the user context changes, for instance on log in/out, you should remember to call setUser again to store the updated username. This feature is optional if you wish it disabled for privacy purposes.

Version tracking

Set the versionName attribute on in your AndroidManifest.xml to be of the form x.x.x.x, where x is a positive integer, and it will be sent with each message. You can then filter by version in the Raygun dashboard.

Getting/setting/cancelling the error before it is sent

This provider has an onBeforeSend API to support accessing or mutating the candidate error payload immediately before it is sent, or cancelling the send outright. This is provided as the public method RaygunClient.setOnBeforeSend(RaygunOnBeforeSend), which takes an instance of a class that implements the RaygunOnBeforeSend interface. Your class needs a public onBeforeSend method that takes a RaygunMessage parameter, and returns the same.

By example:

class BeforeSendImplementation implements RaygunOnBeforeSend {
    @Override
    public RaygunMessage onBeforeSend(RaygunMessage message) {
        Log.i("OnBeforeSend", "About to post to Raygun, returning the payload as is...");
        return message;
    }
}

public class FullscreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Initialize the activity as normal
        RaygunClient.init(getApplicationContext());
        RaygunClient.attachExceptionHandler();
        RaygunClient.setOnBeforeSend(new BeforeSendImplementation());
    }
}

In the example above, the overridden onBeforeSend method will log an info message every time an error is sent.

To mutate the error payload, for instance to change the message:

@Override
public RaygunMessage onBeforeSend(RaygunMessage message) {
    Log.i("onBeforeSend", "Changing the message...");

    RaygunMessageDetails details = message.getDetails();
    RaygunErrorMessage error = details.getError();
    error.setMessage("Mutated message");

    return message;
}

To cancel the send (prevent the error from reaching the Raygun dashboard) by returning null:

@Override
public RaygunMessage onBeforeSend(RaygunMessage message) {
    Log.i("onBeforeSend", "Cancelling sending message to Raygun...");
    return null;
}

Custom error grouping

You can override Raygun's default grouping logic for Android exceptions by setting the grouping key manually in onBeforeSend

@Override
public RaygunMessage onBeforeSend(RaygunMessage message) {
    RaygunMessageDetails details = message.getDetails();
    details.setGroupingKey("foo");

    return message;
}

Any error instances with a certain key will be grouped together. The example above will place all errors within one group (as the key is hardcoded to 'foo'). The grouping key is a String and must be between 1 and 100 characters long. You should send all data you care about (for instance, parts of the exception message, stacktrace frames, class names etc) to a hash function (for instance MD5), then pass that to setGroupingKey.

API

See the GitHub repository for a full list of public initializing, attaching, sending and other methods.

Troubleshooting

  • Not seeing errors in the dashboard?

    Raygun4Android outputs Logcat messages - look for the 'Exception Message HTTP POST result' message - 403 will indicate an invalid API key, 400 a bad message, and 202 will indicate received successfully.

    Also, ensure that you have called attachExceptionHandler() after init(), or provided your own uncaught exception handler that sends using RaygunClient.

  • Environment data

    A selection of enironment data will be attached and available in the Environment tab in the dashboard, and more in the Raw tab. This data is gathered from android.os.Build - if you wish to see more data you can add them on the userCustomData object.

  • What happens when the phone has no internet connection?

    Raygun4Android will save the exception message to disk. When the provider is later asked to send another message it will check if the internet is now available, and if it is, send the cached messages. A maximum of 64 messages will be cached, then overwritten (using a LRU strategy).

Cold Fusion

Documentation - Raygun4cfml - ColdFusion Error Reporting

The raygun4cfml provider

Raygun4cfml is a library that you can add to your ColdFusion/CFML application. Once installed it will transmit all exceptions to your Raygun.com dashboard. Installation only takes a few minutes so you can start receiving error and crash reports right away.

Supported CFML engines:

  • Adobe ColdFusion 9+
  • Railo 4.0+
  • Lucee 4.5+

Current Version: 1.1.0 (Jan 2 2016)

Dependencies: 

  • Testbox 2 (for running unit and BDD tests only)

How do I get started with raygun4cfml?

Installation

Option 1 (preferred):

Use Commandbox and Forgebox to get the library and then follow the ideas outlined in 'Library organisation' for further setup.

To get the latest from the master repository

box install raygun4cfml 

To install a specific release or tag: 

box install git://github.com/MindscapeHQ/raygun4cfml.git#{tagname}

Example tag names are 1.1.0, 1.0.2.0, 1.0.1.0 etc. Please check the list of tags on Github. Be aware that if you install any tag from before I introduced support for Commandbox and Forgebox there won't be a box.json file and therefore Commandbox will give you a warning as well as there won't be any dependency management for such an installation of the library.

Shortcut for the above:

box install MindscapeHQ/raygun4cfml#{tagname}

To get the latest from my development repository (be warned, this might contain all sorts of untested code):

box install TheRealAgentK/raygun4cfml

Option 2:

Fork and clone the repo to your local system. Move the src/test directories into places of your choice and suitable for your system and follow the ideas outlined in 'Library organisation'.

Option 3:

Download a zip file containing the current content of the repo or a release/tag of your choice. Unzip the resulting file. Move the src/test directories into places of your choice and suitable for your system and follow the ideas outlined in 'Library organisation'.

Notes:

(1) Options 2 and 3 will not fulfill any necessary dependencies, you're on your own.

Library Organization & Instantiation

/src contains the source code. The package structure is nz.co.ventego-creative.co.nz.raygun4cfml but the library's components themselves are independent of the package path. Therefore you can use the library in multiple ways:

Put the content of /src into your webroot and instantiate RaygunClient through something like the following:

raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
    apiKey = "YOURAPIKEYHERE"
);

Put the contents of /src into any other place of your choice and create a mapping to /nz in your server administrator or through code and then use the instantiation code as above.

Put the contents of the raygun4cfml into a place of your choice where your CFML has some sort of a mapping pointing towards and and just instantiate RaygunClient like this:

raygun = createObject("component","RaygunClient").init(
    apiKey = "YOURAPIKEYHERE"
);

/samples contains a set of files that show how the library can be used in your code through a global error handler as well as a contributed example for ColdBox 3.6

/tests contains manual tests as well as a structure (but no tests at this stage) for Testbox unit and BDD tests.

Example error handler

The following is an example for use in a global error handler template e.g cferror. It also demonstrates how you can add custom data to every message delivered to Raygun.

<cfscript>
    raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
        apiKey = "YOURAPIKEYHERE"
    );

    result = raygun.send(error);
</cfscript>

Configuration

Tags

Tags can be sent with each error like this:

tags = ["coding","db","sqlfail"];
raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
	apiKey = variables.RAYGUNAPIKEY
);

result = raygun.send(issueDataStruct=error,tags=tags);

Custom Data

Custom data objects can be created and sent with each error:

customUserDataStruct = {"session" = {"memberID" = "5747854", "memberFirstName" = "Kai"}, "params" = {"currentAction" = "IwasDoingThis", "justAnotherParam" = "test"}};
customUserData = createObject("nz.co.ventego-creative.raygun4cfml.RaygunUserCustomData").init(customUserDataStruct);

raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
	apiKey = variables.RAYGUNAPIKEY
);
result = raygun.send(issueDataStruct=error,userCustomData=customUserData);

Sending user data

Data for the affected user which experienced the error can be attached like this:

userIdentifier = createObject("nz.co.ventego-creative.raygun4cfml.RaygunIdentifierMessage").init(Identifier="test@test.com",isAnonymous=false,UUID="47e432fff11",FirstName="Test",Fullname="Tester");
    
raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
	apiKey = variables.RAYGUNAPIKEY
);

result = raygun.send(issueDataStruct=error,user=userIdentifier);

Filtering sensitive data

You can remove sensitive data (e.g financial data or credentials) from error payloads using a content filter:

filter = [{filter = "password", replacement = "__password__"}, {filter = "creditcard", replacement = "__ccnumber__"}];
contentFilter = createObject("nz.co.ventego-creative.raygun4cfml.RaygunContentFilter").init(filter);

raygun = createObject("component","nz.co.ventego-creative.raygun4cfml.RaygunClient").init(
    apiKey =  variables.RAYGUNAPIKEY,
    contentFilter = contentFilter
);

result = raygun.send(error);

Raygun4cfml GitHub Repository

To get the source code, visit the GitHub repository here.

Drupal

Documentation - Raygun4Drupal - Drupal Error Reporting

Raygun for Drupal is available from: https://www.drupal.org/project/raygun

Raygun for Drupal offers easy codeless setup of error and crash reporting for your Drupal application.

Requirements

This module requires:

  • PHP 5.3+
  • You have downloaded the raygun4php library (found at https://github.com/MindscapeHQ/raygun4php) to your `sites/all/libraries` directory under a sub folder `raygun`.

The libraries directory should look like:

sites/all/libraries
-- raygun
---- RaygunClient.php
---- RaygunEnvironmentMessage.php
....

The easiest way to do this is to navigate to the sites/all/libraries folder (creating it if doesn't already exist) and running the following commands:

mkdir raygun

git clone https://github.com/mindscapehq/raygun4php.git

mv -f raygun4php/src/Raygun4php/* raygun/

And optionally (to clean the directory):

rm -rf raygun4php

Installing the Module

Logging into the admin panel of Drupal and access the Modules page, click Install new module

Paste the download link of the module, this should look like this: http://ftp.drupal.org/files/projects/raygun-7.x-1.1.tar.gz

Enable the Module on the Modules page.

Follow the Configure link and paste your API key into the API key section, you can configure some other options here as well.

After saving the configuration Raygun should be live and will collect any errors which occur on your Drupal site.

 

Go

Documentation - Raygun4go - Go error reporting

About

raygun4go adds Raygun-based error handling to your golang code. It catches all occuring errors, extracts as much information as possible and sends the error to Raygun where it is viewable in the Crash Reporting dashboard.

Contents

Getting Started

Installation

$ go get github.com/MindscapeHQ/raygun4go

Basic Usage

Include the package and then defer the HandleError-method as soon as possible in a context as global as possible. In webservers, this will probably be your request handling method, in all other programs it should be your main-method. Having found the right spot, just add the following example code:

raygun, err := raygun4go.New("appName", "apiKey")
if err != nil {
  log.Println("Unable to create Raygun client:", err.Error())
}
raygun.Silent(true)
defer raygun.HandleError()

where appName is the name of your app and apiKey is your Raygun-API-key. If your program runs into a panic now (which you can easily test by adding panic("foo") after the call to defer), the handler will print the resulting error message. If you remove the line

raygun.Silent(true)

the error will be sent to Raygun using your API-key.

Options

The client returned by New has several chainable option-setting methods:

Silent(bool)

If set to true, this prevents the handler from sending the error to Raygun, printing it instead.

Request(*http.Request)

Adds the responsible http.Request to the error.

Version(string)

If your program has a version, you can add it here.

Tags([]string)

Adds the given tags to the error. These can be used for filtering later.

CustomData(interface{})

Add arbitrary custom data to you error. Will only reach Raygun if it works with json.Marshal().

User(string)

Add the name of the affected user to the error.

GitHub repository

You can find the source code for this library at https://github.com/MindscapeHQ/raygun4go. If you have any issues or feature requests you can add them there, or by clicking on the Feedback button in the Raygun web app's sidebar.

iOS

Documentation - Raygun4iOS - iOS Error & Crash Reporting

Raygun crash reporting and error monitoring is available for iOS with the raygun4iOS provider. The raygun4iOS provider can be used in Objective-C and Swift iOS applications. The setup instructions below includes steps to integrate Raygun4iOS in both types of applications. The features described in these docs also apply to both languages.

Setup instructions (Using CocoaPods)

Raygun can be obtained through CocoaPods which is an iOS dependency manager. Read more about CocoaPods here, or see further below for the manual setup instructions.

1. Update Podfile

Add the following to your project's Podfile:

platform :ios
pod 'Raygun4iOS'

2. Run pod install

Open a shell, navigate to the location of your project's Podfile and run:

pod install

From now on, make sure to always open the Xcode workspace instead of the project file when building your project.

3. Import dependency

In AppDelegate.m, import the Raygun.h header:

#import <Raygun4iOS/Raygun.h>

4. Start the Raygun error reporter

In the application function of AppDelegate.m, add the following code to start the Raygun error reporter. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

[Raygun sharedReporterWithApiKey:@"YOUR_API_KEY_HERE"];

The steps above will cause all unhandled exceptions to be sent to your Raygun account.

Toubleshooting

If your project does not build after performing these steps, your projects "Other Linker Flags" option is most likely overriding the Pods project option. (You'd get a warning about this after running pod install). To fix this, click your project in Xcode, and then select your main app target. Go to the "Build Settings" tab, search for "Other Linker Flags" and add $(inherited) to this option and you'll be good to go.

Setup instructions (Manual)

If you don't use CocoaPods, follow these instructions to manually download and reference the Raygun4iOS framework.

1. Download Raygun4iOS

Download and unzip the current version from here: Raygun4iOS Version 2.3.4

Change log:

  • Expanded automatic network logging coverage to include NSURLSession methods using NSURLSessionTaskDelegates.
  • Able to enable/disable network logging when using Pulse.
  • Added the ability to filter out data sent for network requests or view load timings 

Legacy versions:

2. Reference Raygun4iOS in your project

In Xcode, click on your project and then select your main app target. Go to the "Build Phases" tab and expand "Link Binary With Libraries". Drag Raygun4iOS.framework into the library list.

3. Import dependency

In AppDelegate.m, import the Raygun.h header:

#import <Raygun4iOS/Raygun.h>

4. Start the Raygun error reporter

In the application function of AppDelegate.m, add the following code to start the Raygun error reporter. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

[Raygun sharedReporterWithApiKey:@"YOUR_API_KEY_HERE"];

5. Link the C++ library

In Xcode, click on your project and then select your main app target. Go to the "Build Settings" tab, search for "Other Linker Flags" and add "-lc++" to this setting.

The steps above will cause all unhandled exceptions to be sent to your Raygun account.

Swift

Swift is another langauge created by Apple for building iOS (and OSX) applications. The same Raygun4iOS provider mentioned above for Objective-C iOS applications can also be used for error reporting in Swift iOS apps.

  1. Installation - same as with Objective-C applications, there are two ways to install Raygun4iOS into your Swift iOS app: via the CocoaPods dependancy manager, or by manually downloading and referencing the library. The CocoaPods instructions and the download link can be found above.
  2. Once your application is referencing the Raygun4iOS library, import Raygun4iOS into the bridging-header file of your Swift app:
    #import <Raygun4iOS/Raygun4iOS.h>
  3. Finally, in AppDelegate.swift, add the following code to the application function:
    [Raygun .sharedReporterWithApiKey("YOUR_APP_API_KEY")]

A complete tutorial of these steps can be found here.

Affected user tracking

Raygun supports tracking the unique users who encounter bugs in your apps. You can transmit the current user who was affected by the exception by calling the identify method on the current raygun client (code example below). You pass a string to this method to represent the user which could be a database id, username, email address or whatever works for you. A count of affected users will then appear in the error statistics in Raygun. If you provide an email address, you will see it on the error page in Raygun, and if they have an associated Gravatar you will see that too. If the user context changes, for instance on log in/out, you should remember to call identify again to store the updated identity. This feature is optional if you wish it disabled for privacy purposes. Below is an example of setting the user identity after the usual Raygun4iOS initialization.

[Raygun sharedReporterWithApiKey:@"YOUR_APP_API_KEY"];
[[Raygun sharedReporter] identify:@"UNIQUE_USER_IDENTITY"];

Custom tags and data

When sending exceptions manually, there is an option to include an array of strings or/and a dictionary of custom data. This data is displayed in your Raygun dashboard when veiwing exception instance data. The tag values are also searchable in your Raygun dashboard so that you can find all exception instances that you've marked with a particular flag. Sending tags and custom data can be done using one of the send method overloads below. In the second overload, the tags array can be nil if you only need to send the data dictionary. Please note: currently the custom data dictionary should only include simple values such as strings and numbers.

[[Raygun sharedReporter] send:exception withTags: array];
[[Raygun sharedReporter] send:exception withTags: array withUserCustomData: dictionary];

Symbolification

The iOS provider transmits encoded crash reports it receives from your app as it runs on devices or emulators. To turn these crash reports into useful data that you can use to debug, Raygun requires your app's dSYM file. This is generated on build in Xcode and is unique to every version of your app's source. When you are finished testing locally and are deploying a new build, you need to upload the new dSYM file corresponding to that build.

Once Raygun has that build's dSYM file, the encoded crash reports will be turned into complete back traces, with line numbers and file names.

Uploading a dSYM file

Here are 3 options for uploading your dSYM files to your Raygun account:

Native dSYM uploading app - Raygun Sidekick

The Raygun Sidekick is a native Mac application that sits in your Mac menu bar which will detect, zip and upload the appropriate dSYM file in just a few clicks. It is highly recommend that you use the Raygun Sidekick rather than tediously uploading the dSYM files yourself as described below.

Download the Raygun Sidekick right here and check out the documentation for more info.

Manual upload

To manually upload dSYM files, visit the Raygun dashboard, click on dSYM Center in the sidebar, then upload the dSYM file by drag 'n dropping or using Finder.

You can do this at any time. If you deploy a new build and Raygun receives crash reports without the dSYM file, it will store them ready for you to upload it. When you do, visit an error from that build and click on 'Reprocess crash report'. After a short delay, the stack trace will appear.

Manual uploading via cURL

For sending dSYMs to Raygun in other processes such as build scripts or the terminal, you can post via cURL:

curl -H "Host: app.raygun.io" -H "Authorization: Basic <token>" --form "DsymFile=@build/${APP_NAME}-${BUILD_NUMBER}-dSYM.zip" https://app.raygun.io/dashboard/${APP_ID}/settings/symbols

where APP_NAME and BUILD_NUMBER make up the name of the zippped dSYM. The APP_ID is available in the URL of your app in the Raygun dashboard.

<token> should be replaced with a basic auth token which can be created by Base64 encoding your Raygun account credentials in the following format (make sure not to forget the colon between them): username:password

Java

Documentation - Raygun4Java - Java Error & Crash Reporting

Contents

The Raygun4Java provider

Raygun crash reporting and error monitoring is easily available with raygun4java. Raygun4java is a library that you can easily add to your Java application, which will then allow you to transmit all exceptions to your Raygun.io dashboard. Installation is painless, and configuring your site to transmit errors takes only 5 minutes.

Raygun4java supports Java 6 and greater. The library is available as a Maven package, so you only need to add the appropriate entry to your pom.xml. JARs are also available for other build systems.

What Java project types are supported?

Pretty much anything! Classical desktop and console apps are supported by the main library. Web applications projects, such as Java Servlets and projects that use JSPs are fully supported by including the additional raygun4java-web library. This can also be used in popular web frameworks such as Spring.

First-class Scala and the Play 2 framework support is also available, and the library can also be used in code running on Google App Engine.

What can I send to Raygun.io?

Raygun4Java is designed to send any object that inherits from Throwable. You can add a set of tags (as an array of strings) to identify a certain type of message, or add a custom user data (as a key-value Map).

What are the steps I need to take to add raygun4java to my application?

Here's an overview:

  1. Add the dependency to your pom.xml, or copy the JAR(s) into a /lib folder and add it to the build path
  2. Create an exception handler and subscribe to it
  3. Add two lines to this handler - one creating an instance of RaygunClient, and the other calling Send() on it. And you're done!

Read the step-by-step instructions below.

Installation

With Maven and Eclipse/another IDE

These instructions assume you have a Maven project with a POM file set up in Eclipse, but this is also applicable to other IDEs and environments.

  1. Open your project's pom.xml in Eclipse. Click on Dependencies -> Add. In the pattern search box, typecom.mindscapehq.
  2. Add com.mindscape.raygun4java and com.mindscapehq.core, version 2.0.0.

    If you are working in a web environment, add com.mindscapehq.webprovider jar too.

    If you wish to grab the example project, you can also get the sampleapp jar.

  3. Save your POM, and the dependencies should appear in Maven Dependencies.

With Maven and a command shell

If you are in a shell/text editor environment, you can run mvn install from the directory containing your project's pom.xml. The pom.xml will need to contain something like:

<dependencies>
    ...
    <dependency>
        <groupId>com.mindscapehq</groupId>
        <artifactId>raygun4java</artifactId>
        <type>pom</type>
        <version>[2.1.1)</version>
    </dependency>
    <dependency>
        <groupId>com.mindscapehq</groupId>
        <artifactId>core</artifactId>
        <version>[2.1.1)</version>
    </dependency>
</dependencies>

POM for Web Projects

If you're using servlets, JSPs or similar, you'll need to also add:

<dependency>
    <groupId>com.mindscapehq</groupId>
    <artifactId>webprovider</artifactId>
    <version>[2.1.1)</version>
</dependency>

With Ant or other build tools

Download the JARs for the latest version from here:

raygun-corerequired

raygun-webprovideroptional - if you want to receive HTTP request data from JSPs, servlets, GAE, web frameworks etc.

gsonrequired - you will also need the Gson dependency in your classpath.

Usage

Desktop applications

To catch all exceptions in your application, and to send them to Raygun:

public class MyApp
{
    public static void main(String[] args) throws Throwable
    {
            Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    }
}

class MyExceptionHandler implements Thread.UncaughtExceptionHandler
{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        RaygunClient client = new RaygunClient("YOUR_APP_API_KEY");
        client.Send(e);

    }
}

Or see the sample app which is where this code originates.

JSPs

The concept is the same for the above - set up an Unhandled Exception handler, then inside it create a RaygunClient and call Send() on it, passing in the exception. The way this is done will vary based on what framework you are using. Presented below is a naive example that just uses plain JSPs - this architecture is obviously not recommended. A similar method will work for raw servlets if happen to be using those.

Inside web.xml

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
        <location>/error.jsp</location>
</error-page>

Inside error.jsp

<%@ page isErrorPage="true" %>
<%@ page import="com.mindscapehq.raygun4java.webprovider.RaygunServletClient" %>

<%
RaygunServletClient client = new RaygunServletClient("YOUR_APP_API_KEY", request);

client.Send(exception);
%>

When an exception is thrown from another JSP, this page will take care of the sending.

Note: all Java dynamic web page projects should have core-2.0.0..jar, webprovider-2.0.0..jar and gson-2.1.jar on their classpath.

Play 2 framework for Java and Scala

This provider now contains a dedicated Play 2 provider for automatically sending Java and Scala exceptions from Play 2 web apps. Feedback is appreciated if you use this provider in a Play 2 app. You can use the plain core-2.x.x provider from Scala, but if you use this dedicated Play 2 provider HTTP request data is transmitted too.

Installation

With SBT

Add the following line to your build.sbt's libraryDependencies:

libraryDependencies ++= Seq(
    "com.mindscapehq" % "raygun4java-play2" % "2.2.0"
)

Usage

For automatic exception sending, in your Play 2 app's global error handler, RaygunPlayClient has a method which allows you to pass in a RequestHeader and send a Throwable. If you have changed your global class in conf/application.conf, the appropriate code below should be placed in that class instead.

In Scala - app/Global.scala:

override def onError(request: RequestHeader, ex: Throwable) = {
  val rg = new RaygunPlayClient("your_api_key", request)
  val result = rg.SendAsync(ex)

  super.onError(request, ex)
}

In Java - app/Global.java:

import play.*;
import play.mvc.*;
import play.mvc.Http.*;
import play.libs.F.*;

import com.mindscapehq.raygun4java.play2.RaygunPlayClient;

import static play.mvc.Results.*;

public class Global extends GlobalSettings {

    private String apiKey = "paste_your_api_key_here";

    public Promise<Result> onError(RequestHeader request, Throwable t) {
        RaygunPlayClient rg = new RaygunPlayClient(apiKey, request);
        rg.SendAsync(t);

        return Promise.<Result>pure(internalServerError(
            views.html.myErrorPage.render(t)
        ));
    }
}

Sending asynchronously

Web projects that use RaygunServletClient can call SendAsync(), to transmit messages asynchronously. When SendAsync is called, the client will continue to perform the sending while control returns to the calling script or servlet. This allows the page to continue rendering and be returned to the end user while the exception message is trasmitted.

SendAsync()

Overloads:

void SendAsync(Throwable throwable)

void SendAsync(Throwable throwable, List tags)

void SendAsync(Throwable throwable, List tags, Map userCustomData)

This provides a huge speedup versus the blocking Send() method, and appears to be near instantaneous from the user's perspective.

No HTTP status code is returned from this method as the calling thread will have terminated by the time the response is returned from the Raygun API. A logging option will be available in future.

This feature is considered to be in Beta, and it is advised to test it in a staging environment before deploying to production. When in production it should be monitored to ensure no spurious behaviour (especially in high traffic scenarios) while the feature is in beta. Feedback is appreciated.

Google app engine: This method will not work from code running on GAE - see the troubleshooting section below.

Custom user data and tags

To attach custom data or tags, use these overloads on Send:

RaygunClient client = new RaygunClient("apikey");
Exception exception;

ArrayList tags = new ArrayList<String>();
tags.add("tag1");

Map<string, int> userCustomData = new HashMap<string, int>();
userCustomData.put("data", 1);

client.Send(exception, tags);
// or
client.Send(exception, tags, userCustomData);

Tags can be null if you only wish to transmit custom data. Send calls can take these objects inside a catch block (if you want one instance to contain specific local variables), or in a global exception handler (if you want every exception to contain a set of tags/custom data, initialized on construction).

Affected user tracking

You can call client.SetUser(RaygunIdentifier) to set the current user's data, which will be displayed in the dashboard. There are two constructor overloads available, both of which requires a unique string as the uniqueUserIdentifier. This should be the user's email address if available, or an internally unique ID representing the users. Any errors containing this string will be considered to come from that user.

The other overload contains all the available properties, some or all of which can be null and can be also be set individually on the RaygunIdentifier object.

The previous method, SetUser(string) has been deprecated as of 1.5.0.

Version tracking

Raygun4Java reads the version of your application from your manifest.mf file in the calling package. It first attempts to read this from Specification-Version, then Implementation-Version if the first doesn't exist.

A SetVersion(string) method is also available to manually specify this version (for instance during testing). It is expected to be in the format X.X.X.X, where X is a positive integer.

Getting/setting/cancelling the error before it is sent

This provider has an OnBeforeSend API to support accessing or mutating the candidate error payload immediately before it is sent, or cancelling the send outright.

This is provided as the public method RaygunClient.SetOnBeforeSend(RaygunOnBeforeSend), which takes an instance of a class that implements the RaygunOnBeforeSend interface. Your class needs a public OnBeforeSend method that takes a RaygunMessage parameter, and returns the same.

By example:

class BeforeSendImplementation implements RaygunOnBeforeSend {
    @Override
    public RaygunMessage OnBeforeSend(RaygunMessage message) {
        // About to post to Raygun, returning the payload as is...
        return message;
    }
}

class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    public void uncaughtException(Thread t, Throwable e) {
        RaygunClient client = new RaygunClient("paste_your_api_key_here");
        client.SetOnBeforeSend(new BeforeSendImplementation());
        client.Send(e, tags, customData);
    }
}


public class MyProgram {
    public static void main(String[] args) throws Throwable {
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    }
}

In the example above, the overridden `OnBeforeSend` method will log an info message every time an error is sent.

To mutate the error payload, for instance to change the message:

@Override
public RaygunMessage OnBeforeSend(RaygunMessage message) {
    RaygunMessageDetails details = message.getDetails();
    RaygunErrorMessage error = details.getError();
    error.setMessage("Mutated message");

    return message;
}

To cancel the send (prevent the error from reaching the Raygun dashboard) by returning null:

@Override
public RaygunMessage OnBeforeSend(RaygunMessage message) {
    //Cancelling sending message to Raygun...
    return null;
}

Custom error grouping

You can override Raygun's default grouping logic for Java exceptions by setting the grouping key manually in OnBeforeSend (see above):

@Override
public RaygunMessage OnBeforeSend(RaygunMessage message) {
    RaygunMessageDetails details = message.getDetails();
    details.setGroupingKey("foo");
    return message;
}

Any error instances with a certain key will be grouped together. The example above will place all errors within one group (as the key is hardcoded to 'foo'). The grouping key is a String and must be between 1 and 100 characters long. You should send all data you care about (for instance, parts of the exception message, stacktrace frames, class names etc) to a hash function (for instance MD5), then pass that to setGroupingKey.

Troubleshooting

  • When Maven runs the tests locally, Surefire might complain of unsupported major.minor version 51.0 - ensure you have JDK 7 set as your JAVA_HOME, or set the plugin goal for maven-surefire-plugin to be <configuration><jvm>${env.your_jre_7_home}/bin/java.exe</jvm></configuration> in the parent pom.

  • Google App Engine: Raygun4Java is confirmed to work with projects built with GAE, however only limited environment data is available due to JDK library restrictions. The SendAsync methods also will not work, however you can place the Send() call in the Run() body of a background thread, or one of the other threading features in the App Engine API.

Raygun4java GitHub Repository

For complete installation instructions, getting the source code and troubleshooting, visit the GitHub repository here.

JavaScript

Documentation - JavaScript Error Tracking With Raygun

Javascript error tracking with Raygun is available using the Raygun4js provider. 

Raygun4js is a library that you can easily add to your website or web application, which will then monitor your application and display all JavaScript errors affecting your users within your Raygun dashboard. Installation is painless, and configuring your site to transmit errors takes only five minutes.

The provider is a single script which includes the sole dependency, allowing you to drop it straight in. It is also available as a script snippet which loads the library from Raygun's CDN.

The provider is open source and available at Raygun4JS GitHub repository.

How do I track Javascript errors using Raygun?

Raygun4js has two main functions, the first to transmit JavaScript errors manually caught in try-catch blocks, and the second which is a handler to catch and send all errors caught in window.onerror.

Supported browsers and platforms

Modern browsers are supported out-of-the-box. Auto-updating versions of Chrome, Firefox, IE10+, Safari and Opera. IE 8 and 9 are also supported (the former requires the allowInsecureSubmissions option). Pulse requires IE >= 9 for Navigation Timing API support.

Raygun4JS also has dedicated support for WinJS, and works on various Android browsers and smart TVs. Support for React Native and other bundled mobile frameworks is available.

It is also known to run on old versions of Firefox (pre 4.0) and Opera. Legacy browsers such as Netscape, IE <= 7 are supported on a best-effort basis. Naturally, browsers that do not have JavaScript enabled are incompatible.

Contents

Getting Started

Step 1

Add this snippet to your markup, before the closing </head> tag:

<script type="text/javascript">
  !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
  (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
  f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
  h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
  e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");
</script>

This will fetch the Raygun4js script from our CDN asynchronously, so it doesn't block the page load. It will also catch errors that are thrown while the page is loading, and send them when the script is ready.

Step 2

Add the following lines to your JavaScript site code just before the closing body tag and paste in your API key (from your Raygun dashboard), to set up the provider to automatically send errors to your Raygun account:

<script type="text/javascript">
  rg4js('apiKey', 'paste_your_api_key_here');
  rg4js('enableCrashReporting', true);
</script>

This will configure the provider to automatically send all unhandled JavaScript errors to Raygun.

That's it for the basic setup! See Usage below for more info on how to send errors.

Alternative setup options

Note: This library can now be interacted with in two ways, the V1 API and the V2 API. The V1 API is available as 'public' functions on the global Raygun object, and is intended to be used to control the provider during runtime. Legacy setup methods remain on this API for backwards compatibility with 1.x releases. The V2 API is made available when using the snippet (above), and is used to asynchronously configure the provider during onLoad. This is the recommended approach for new setups.

If you are installing the provider locally using a package manager or manually, you can either use the V2 API by adding the snippet and replace the second-last parameter with the URL of your hosted version of the script, or use the V1 API. The snippet/V2 approach does not support the script being bundled with other vendor scripts, but the V1 API does.

Snippet without page load error handler

If you do not want errors to be caught while the page is loading, use this snippet here.

Synchronous methods

Bower

Using the Bower package manager, you can install it by running this command in a shell:

bower install raygun4js

NPM

npm install raygun4js --save

This lets you require the library with tools such as Webpack or Browserify.

NuGet

Visual Studio users can get it by opening the Package Manager Console and typing:

Install-Package raygun4js

CDN

Raygun4JS can also be loaded directly from our content delivery network:

<script type="text/javascript" src="//cdn.raygun.io/raygun4js/raygun.min.js"></script>

It is available using HTTP or HTTPS.

The current release is always available in /raygun4js/, while previous releases are available as subdirectories, for instance /raygun4js/1.14.0/raygun.js. The vanilla versions are also available as below.

Note that the CDN's current unversioned release (/raygun4js/raygun.js) may lag behind the package managers by around a week, to ensure stability. When a new version is released, this will be available immediately from its versioned folder as above.

React Native/Webpack/as a UMD module

React Native and other bundled app frameworks that uses packaging/module loading libraries can use Raygun4JS as a UMD module:

// Install the library

npm install raygun4js --save

// In a central module (as early as possible), reference and install the library with either this syntax:
import rg4js from 'raygun4js';
// Or this syntax:
var rg4js = require('raygun4js');

// Then set your config options (in one module only)
rg4js('enableCrashReporting', true);
rg4js('apiKey', 'paste_your_api_key_here');

All unhandled JavaScript errors will then be sent to Raygun. You can then import rg4js from 'raygun4js' in any other modules and use the rest of the V2 API below - including rg4js('send', anErrorObject) for manual error sending.

Note that the UMD module has a major limitation for web applications as errors that occur during page load in the bundle before the Raygun dependency is executed, such as syntax errors or runtime errors, can't be caught and sent. Also, Pulse timings may be severly disrupted. Thus, the HTML snippet at the end of </head> is greatly preferred to ensure you don't miss any errors and for data correctness. The tradeoff with this method is that it is slightly less idiomatic to call rg4js as a global variable without importing/requiring it. As such, we only recommend this approach for React Native and other bundled mobile app (non-web) frameworks.

Manual download

Download the production version or the development version.

You can also download a version without the jQuery hooks if you are not using jQuery or you wish to provide your own hooks. Get this as a production version or development version.

Usage

To send errors manually:

Raygun.init("apikey");

try {
  throw new Error("Description of the error");
} catch (e) {
  Raygun.send(e)
}

In order to get stack traces, you need to wrap your code in a try/catch block like above. Otherwise the error hits window.onerror handler and may only contain the error message, line number, and column number.

You also need to throw errors with throw new Error('foo') instead of throw 'foo'.

To automatically catch and send unhandled errors, you can attach the automatic window.onerror handler callback:

// V2
rg4js('enableCrashReporting', true);

// V1
Raygun.attach();

If you need to detach it from window.onerror (which will disable automatic unhandled error sending):

Raygun.detach();

IE8

If you are serving your site over HTTP and want IE8 to be able to submit JavaScript errors then you will need to set the following setting which will allow IE8 to submit the error over HTTP. Otherwise the provider will only submit over HTTPS which IE8 will not allow while being served over HTTP.

// V2
rg4js('options', {
  allowInsecureSubmissions: true
});

// V1
Raygun.init('yourApiKey', { allowInsecureSubmissions: true });

Enabling Pulse

To enable Pulse (Real User Monitoring), make this call:

rg4js('enablePulse', true);

Documentation

Legacy V1 documentation

The old documentation for the V1 API (Raygun.send() etc) is available here.

Differences between Raygun4JS V1.x and V2+

This provider supports two APIs for interacting with the provider, V1 and V2.

V1 remains unchanged from previous versions, and all current code is backwards compatible. This API is of the form where functions can be called on the global Raygun object, for instance Raygun.init('your_apikey').attach().

V2 supports a new API for interacting with the script as it is loaded using the asynchronous snippet. A new global function is made available, rg4js() (configurable), which accepts parameters that are applied to the provider once it is download asynchronously. This API is of the form rg4js('init', 'your_apikey').

Using the snippet to fetch the script from the CDN, along with the V2 API, is superior as errors that occur while the page is loading but Raygun4JS hasn't been downloaded will now be caught. With any of the synchronous methods these will not be sent to Raygun, and the script load will block the page load. Thus, you should use the snippet, the CDN and the V2 API for the best experience for your users.

For initial setup, all functions are interchangeable and available using either method. The public functions available on the global Raygun object can be accessed by calling rg4js(functionName, value) and vice versa (with the exception of send()).

For mutating the provider after initial setup, you can interact with the global Raygun object after page load. By example with plain jQuery:

$(window).load(function () {
  Raygun.withTags(["Loaded"]);
});

Initialization options

To configure the provider, call one of these and pass in an options object:

// V2
rg4js('options', {
  // Add some or all of the options below
});

// V1
Raygun.init('your_apikey', {
  // Add some or all of the options below
});

The second parameter should contain one or more of these keys and a value to customize the behavior:

allowInsecureSubmissions - posts error payloads over HTTP. This allows IE8 to send JS errors.

ignoreAjaxAbort - User-aborted Ajax calls result in errors - if this option is true, these will not be sent.

ignoreAjaxError - Ajax requests that return error codes will not be sent as errors to Raygun if this option is true.

debugMode - Raygun4JS will log to the console when sending errors.

ignore3rdPartyErrors - ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. This option removes nonsense 'Script Error's from your Raygun dashboard.

wrapAsynchronousCallbacks - disables wrapping of async setTimeout/setInterval callbacks when set to false. Defaults to true. This option is respected when attach() is called.

excludedHostnames - Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested.

excludedUserAgents - Prevents errors from being sent from certain clients, based on their user agent string. Pass in an array of strings or RegExp objects. Useful for ignoring headless browsers in unit testing, or old/problematic clients.

disableAnonymousUserTracking - Prevent user data being sent for anonymous users (those where setUser hasn't been called).

disableErrorTracking - Prevent all errors from being sent.

disablePulse - Prevent Pulse real user monitoring events from being sent.

apiEndpoint - A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this.

pulseMaxVirtualPageDuration - The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes).

pulseIgnoreUrlCasing - Ignore URL casing when sending data to Pulse.

An example:

Raygun.init('apikey', {
  allowInsecureSubmissions: true,
  ignoreAjaxAbort: true,
  ignoreAjaxError: true,
  debugMode: true,
  ignore3rdPartyErrors: false,
  wrapAsynchronousCallbacks: true,
  excludedHostnames: ['localhost', '\.dev'],
  excludedUserAgents: ['PhantomJS', 'MSIE'],
  disableErrorTracking: false,
  disablePulse: false,
  pulseMaxVirtualPageDuration: 1800000
  pulseIgnoreUrlCasing: false
}).attach();

Pulse API

Tracking Single Page Application view change events

Raygun Pulse supports client-side SPAs through the trackEvent function:

// V2
rg4js('trackEvent', {
  type: 'pageView',
  path: '/' + window.location.pathname // Or perhaps window.location.hash
});

// V1
Raygun.trackEvent('pageView', { path: '/' + foo });

When a route or view change is triggered in your SPA, this function should be called with type being pageView and pathset to a string representing the new view or route. Pulse will collect up all timing information that is available and send it to the dashboard. These are then viewable as 'virtual pages'.

The following are a couple of configuration examples that you can use or adapt for your client-side view library/framework. Naturally, if you are using a more full-featured routing system, you should trigger a pageView inside there when the route changes.

jQuery

// V2
$(window).hashchange(function() {
  rg4js('trackEvent', {
      type: 'pageView',
      path: '/' + location.hash
  });
});

// V1
$(window).hashchange(function() {
  Raygun.trackEvent('pageView', {
    path: '/' + location.hash
  });
});

AngularJS

// V2
$scope.$on('$routeChangeSuccess', function () {
  rg4js('trackEvent', {
      type: 'pageView',
      path: '/' + $scope.area
  });
});

// V1
app.run([‘$rootScope’, ‘$window’, ‘$location’, trackPageView]);

function trackPageView($rootScope, $window, $location){
  // watch for successful state transitions
  $rootScope.$on(‘$locationChangeSuccess’, function (event, current) {
    $window.Raygun.trackEvent(‘pageView’, {
      path: $location.url()
    });
  });
}

Multiple Raygun objects on a single page

You can have multiple Raygun objects in global scope. This lets you set them up with different API keys for instance, and allow you to send different errors to more than one application in the Raygun web app. To create a new Raygun object and use it call:

// V2
var secondRaygun = rg4js('getRaygunInstance').constructNewRaygun();
secondRaygun.init('apikey');
secondRaygun.send(...);

// V1
var secondRaygun = Raygun.constructNewRaygun();
secondRaygun.init('apikey');
secondRaygun.send(...)

Only one Raygun object can be attached as the window.onerror handler at one time, as onerror can only be bound to one function at once. Whichever Raygun object had attach() called on it last will handle the unhandle errors for the page. Note that you should use the V1 API to send using the second Raygun object, and it should be created and called once the page is loaded (for instance in an onload callback).

NoConflict mode

If you already have an variable called Raygun attached to window, you can prevent the provider from overwriting this by enabling NoConflict mode:

// V2
rg4js('noConflict', true);

// V1
Raygun.noConflict();

To then get an instance of the Raygun object when using V2, call this once the page is loaded:

var raygun = rg4js('getRaygunInstance');

Callback events

onBeforeSend

// V2
rg4js('onBeforeSend', function (payload) {
  return payload;
});

// V1
Raygun.onBeforeSend(function (payload) {
  return payload;
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be called immediately before the payload is sent. The one parameter it gets will be the payload that is about to be sent. Thus from your function you can inspect the payload and decide whether or not to send it.

From the supplied function, you should return either the payload, or return false.

If your function returns a truthy object, Raygun4JS will attempt to send it as supplied. Thus, you can mutate it as per your needs - preferably only the values if you wish to filter out data that is not taken care of by filterSensitiveData(). You can also of course return it as supplied.

If, after inspecting the payload, you wish to discard it and abort the send to Raygun, simply return false. By example:

// V2
var myBeforeSend = function (payload) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

rg4js('onBeforeSend', myBeforeSend);

// V1
var myBeforeSend = function (payload) {
  console.log(payload); // Modify the payload here if necessary
  return payload; // Return false here to abort the send
}

Raygun.onBeforeSend(myBeforeSend);

onAfterSend

rg4js('onAfterSend', function (xhrResponse) {
  // Inspect the XHR response here
});

Call this function and pass in a function which takes one parameter (see the example below). This callback function will be immediately called after the XHR request for a Crash Reporting or Pulse event responds successfully, or errors out (its onerror was called). You can inspect the one parameter, which is the XHR object containing the HTTP response data.

onBeforeXHR

// V2
rg4js('onBeforeXHR', function (xhr) {
  // Mutate the xhr parameter as per your needs
});

// V1
Raygun.onBeforeXHR(function (xhr) { });

Call this function when you want control over the XmlHttpRequest object that is used to send error payloads to the API. Pass in a callback that receives one parameter (which is the XHR object). Your callback will be called after the XHR object is opened, immediately before it is sent.

For instance, you can use this to add custom HTTP headers.

Custom error grouping

You can control custom grouping for error instances by passing in a callback. This will override the automatic grouping and be used to group error instances together. Errors with the same key will be placed within the same error group. The callback's signature should take in the error payload, stackTrace and options and return a string, ideally 64 characters or less. If the callback returns null or or a non-string the error will be grouped using Raygun's server side grouping logic (this can be useful if you only wish to use custom grouping for a subset of your errors).

var groupingKeyCallback = function (payload, stackTrace, options) {
  // Inspect the above parameters and return a hash derived from the properties you want

  return payload.Details.Error.Message; // Naive message-based grouping only
};

// V2
rg4js('groupingKey', groupingKeyCallback);

// V1
Raygun.groupingKey(groupingKeyCallback);

Sending custom data

The Raygun object has a withCustomData() function where you can pass in JavaScript objects that will be sent with each error that occurs. This allows you to provide any useful data that is global or in scope.

There are two ways to do this:

On initialization:

// V2
rg4js('withCustomData', { custom: 'data' });

// V1
Raygun.withCustomData({ custom: 'data' });

This custom data is set at initialization, and will be present and static on every Error that is sent.

During a send:

You can also pass custom data with manual send calls, with an options object. This lets you add variables that are in scope or global when handled in catch blocks. For example:

// V2
rg4js('send', {
  error: e,
  customData: [{ foo: 'bar' }];
});

// V1
Raygun.send(err, customData)

This custom data can contain whatever is in scope when you are sending manually.

customData can be an object or an array:

If an object is passed in the Custom Data tab in the dashboard will display the keys with the values nested below.

If an array is passed in their index will be displayed with the values below.

Either may contain further JavaScript objects, strings, numbers, dates and so on.

Providing custom data with a callback

To send the state of variables at the time an error occurs, you can pass withCustomData a function. This needs to return an object. By example:

var desiredNum = 1;

function getMyData() {
 return { num: desiredNum };
}

// V2
rg4js('withCustomData', getMyData);

// V1
Raygun.init('apikey').attach().withCustomData(getMyData);

desiredNum++;

When an error is thrown, the custom data will contain a 'num' key with a value of 2.

getMyData will be called when Raygun4JS is about to send an error, which will construct the custom data. This will be merged with any custom data provided on a Raygun.send() call.

Adding tags

The Raygun dashboard can also display tags for errors. These are arrays of strings or Numbers. This is done similar to the above custom data, like so:

On initilization:

// V2
rg4js('withTags', ['tag1', 'tag2']);

// V1
Raygun.init('apikey').withTags(array)

During a Send:

rg4js('send', {
  error: e,
  tags: ['tag3'];
});

Adding tags with a callback function

As above for custom data, withTags() can now also accept a callback function. This will be called when the provider is about to send, to construct the tags. The function you pass to withTags() should return an array (ideally of strings/Numbers/Dates).

Affected User tracking

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored as a cookie. If the current user changes, to reset it and assign a new ID you can call:

// V2
rg4js('getRaygunInstance').resetAnonymousUser();

// V1
Raygun.resetAnonymousUser();

Disabling anonymous user tracking

// V2
rg4js('options', { disableAnonymousUserTracking: true });

// V1
Raygun.init('apikey', { disableAnonymousUserTracking: true });

Rich user data

You can provide data about the currently logged in user to Raygun by calling:

// V2
rg4js('setUser', {
  identifier: 'user_email_address@localhost.local',
  isAnonymous: false,
  email: 'emailaddress@localhost.local',
  firstName: 'Foo',
  fullName: 'Foo Bar',
  uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55'
});

// V1
Raygun.setUser('user_email_address@localhost.local', false, 'user_email_address@localhost.local', 'Foo', 'Foo Bar', 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55');

Only identifier or the first parameter is required. This method takes additional parameters that are used when reporting over the affected users. the full method signature is:

setUser: function (user, isAnonymous, email, fullName, firstName, uuid)

user is the user identifier. This will be used to uniquely identify the user within Raygun. This is the only required parameter, but is only required if you are using user tracking.

isAnonymous is a bool indicating whether the user is anonymous or actually has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind.

email is the user's email address.

fullName is the user's full name.

firstName is the user's first or preferred name.

uuid is the identifier of the device the app is running on. This could be used to correlate user accounts over multiple machines.

This will be transmitted with each message. A count of unique users will appear on the dashboard in the individual error view. If you provide an email address, the user's Gravatar will be displayed (if they have one). This method is optional; if it is not called no user tracking will be performed. Note that if the user context changes (such as in an SPA), you should call this method again to update it.

Resetting the user:

You can now pass in empty strings (or false to isAnonymous) to reset the current user for login/logout scenarios.

Anonymous user tracking

By default, Raygun4JS assigns a unique anonymous ID for the current user. This is stored as a cookie. If the current user changes, to reset it and assign a new ID you can call:

Raygun.resetAnonymousUser();

Disabling anonymous user tracking

// V2
rg4js('options', { disableAnonymousUserTracking: true });

// V1
Raygun.init('apikey', { disableAnonymousUserTracking: true });

Version filtering

You can set a version for your app by calling:

// V2
rg4js('setVersion', '1.0.0.0');

// V1
Raygun.setVersion('1.0.0.0');

This will allow you to filter the errors in the dashboard by that version. You can also select only the latest version, to ignore errors that were triggered by ancient versions of your code. The parameter should be a string in the format x.x.x if you want to get the version sorting in Raygun to work nicely, where x is a non-negative integer.

Filtering sensitive data

You can blacklist keys to prevent their values from being sent it the payload by providing an array of key names:

// V2
rg4js('filterSensitiveData', ['password', 'credit_card']);

// V1
Raygun.filterSensitiveData(['password', 'credit_card']);

If any key matches one in the input array, its value will be replaced with [removed by filter].

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

rg4js('filterSensitiveData', [creditCardDataRegex]);

Change filter scope

By default this is applied to the UserCustomData object only (legacy behavior). To apply this to any key-value pair, you can change the filtering scope:

// V2
rg4js('setFilterScope', 'all'); // Filter any key in the payload
rg4js('setFilterScope', 'customData'); // Just filter the custom data (default)

// V1
Raygun.setFilterScope('all');

You can also pass RegExp objects in the array to filterSensitiveData, for controllable matching of keys:

var creditCardDataRegex = /credit\D*/; // Remove any keys that begin with 'credit'

// V2
rg4js('filterSensitiveData', [creditCardDataRegex]);

// V1
Raygun.filterSensitiveData([creditCardDataRegex]);

Source maps

Raygun4JS features source maps support through the transmission of column numbers for errors, where available. This is confirmed to work in recent version of Chrome, Safari and Opera, and IE 10 and 11. See the source maps documentation to the left for more information.

Raygun.init('yourApiKey', { allowInsecureSubmissions: true });

Offline saving

The provider has a feature where if errors are caught when there is no network activity they can be saved (in Local Storage). When an error arrives and connectivity is regained, previously saved errors are then sent. This is useful in environments like WinJS, where a mobile device's internet connection is not constant.

Offline saving is disabled by default. To get or set this option, call the following after your init() call:

// V2
rg4js('saveIfOffline', true);

// V1
Raygun.saveIfOffline(true);

If an error is caught and no network connectivity is available (the Raygun API cannot be reached), or if the request times out after 10s, the error will be saved to LocalStorage. This is confirmed to work on Chrome, Firefox, IE10/11, Opera and WinJS.

Limited support is available for IE 8 and 9 - errors will only be saved if the request times out.

Errors in scripts hosted on other domains

Browsers have varying behavior for errors that occur in scripts located on domains that are not the origin. Many of these will be listed in Raygun as 'Script Error', or will contain junk stack traces. You can filter out these errors with the following code snippet. There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

// V2
rg4js('options', { ignore3rdPartyErrors: true });

// V1
Raygun.init('apikey', { ignore3rdPartyErrors: true });

Whitelisting Domains

There is also an option to whitelist domains which you do want to allow transmission of errors to Raygun, which accepts the domains as an array of strings:

rg4js('options', { ignore3rdPartyErrors: true });
rg4js('whitelistCrossOriginDomains', ['code.jquery.com']);

This can be used to allow errors from remote sites and CDNs.

The provider will default to attempt to send errors from subdomains - for instance if the page is loaded from foo.com, and a script is loaded from cdn.foo.com, that error will be transmitted on a best-effort basis.

To get full stack traces from cross-origin domains or subdomains, these requirements should be met:

  • The remote domain should have Access-Control-Allow-Origin set (to include the domain where raygun4js is loaded from).

  • For Chrome the script tag must also have crossOrigin="Anonymous" set.

  • Recent versions of Firefox (>= 31) will transmit errors from remote domains will full stack traces if the header is set (crossOrigin on script tag not needed).

In Chrome, if the origin script tag and remote domain do not meet these requirements the cross-origin error will not be sent.

Other browsers may send on a best-effort basis (version dependent) if some data is available but potentially without a useful stacktrace. The provider will cancel the send if no data is available.

Browser behaviour

Depending on what browser your users are running, the above properties may or may not have an effect. This sums up the situation as of writing:

  • Chrome 30+
  • Firefox 13+
  • Opera 12.50+
  • Safari (at least 6+)

In these browsers, if the script attribute is present, the HTTP header will need to be also present, otherwise the script will be blocked.

Firefox has additional behavior for RuntimeErrors. These will be provided to window.onerror regardless of the two properties, as these aren’t considered a security risk. SyntaxErrors, however, will be blocked in both Gecko and WebKit browsers, if crossorigin is present but the associated cross-origin domain lacks the header.

  • Internet Explorer <= 10

Errors will be reported with all available data in IE 10 and below.

  • Internet Explorer 11+

Third-party errors will not contain any data, and the attributes are not respected at current time.

Limitations of stack trace data

Due to browser API and security limitations, in cases where the message is 'Script error', only one stack trace frame may be present. In this scenario, the line number may not reflect the actual position where the original error was thrown.

For more information, check out this blog post on CORS requirements for Script Errors here.

AngularJS

You can hook failed Ajax requests with $http in AngularJS by providing an Interceptor that sends to Raygun on error. One possible simple implementation:

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'requestError': function(rejection) {
       Raygun.send(new Error('Failed $http request', rejection));
    },

    'responseError': function(rejection) {
       Raygun.send(new Error('Failed $http response', rejection));
    }
  };
});

For more information, see the official docs under Interceptors.

React Native

Note: Support for Crash Reporting in React Native is currently in beta. The current beta version is 2.6.0-SNAPSHOT.6; this reference in your package.json should be updated when a new release is available.

Firstly, add the library to your project:

npm install --save raygun4js@2.6.0-SNAPSHOT.6

Then in a central component (e.g index.ios.js/index.android.js), import the library:

import rg4js from 'raygun4js';

Next, configure the provider using your Raygun application's API key. These lines should be called once only early on when your app boots, for example:

export default class YourReactNativeProject extends Component {
  constructor() {
    super()

    rg4js('enableCrashReporting', true);
    rg4js('apiKey', 'add_your_api_key_here');

    // Put any other rg4js() options you want to set here

    rg4js('boot'); // This call must be made last to start the provider
  }
}

Naturally, you can factor the above logic out into a function or separate component, which should be called early on from your main app component.

Finally, see Source Maps below for how to get your minified JS errors mapped back to human-readable stacktraces.

Affected user tracking

You can optionally configure user tracking, either anonymously or non-anonymously (if your app has the concept of a logged-in user and their data available). Here's an example of how to set it up:

constructor() {
    super()

    rg4js('enableCrashReporting', true);
    rg4js('apiKey', 'paste_your_api_key_here');

    this.setupUser();
  }

  setupUser() {
    try {
      var user;
      AsyncStorage.getItem('@raygun:user', (err, result) => {
        if (!result) {
          // One approach is to load the user data from AsyncStorage or the network using fetch(). When that data returns, place the following in its callback:

          user = {
            identifier: 'user@example.com', // A unique ID or email address, or a random ID such as a UUID
            isAnonymous: false, // Or true
            email: 'user@example.com', // Optional
            firstName: 'Foo', // Optional
            fullName: 'Foo Bar', // Optional
            uuid: 'BAE62917-ACE8-ab3D-9287-B6A33B8E8C55' // Optional device identifier
          };

          AsyncStorage.setItem('@raygun:user', JSON.stringify(user), () => { });
        } else {
          user = result;
        }
        
        rg4js('setUser', JSON.parse(user));
        rg4js('boot'); // Ensure this is called finally
      });

    } catch (e) {
    }
  }

Manual error sending

You can manually send an error that you handle in a catch block in a component, by importing 'rg4js' and calling send. The provider should have already been imported and configured (as above) before the code below is called.

import rg4js from 'raygun4js';

export default class YourChildComponent extends Component {

  constructor() {
    try {
      // Bug goes here
    } catch (e) {
      rg4js('send', e);
    }
  }

}

 

Source maps

For iOS:

Run this command from your project's root directory to build your app JS bundle with source maps:

react-native bundle --platform ios --dev false --entry-file index.ios.js --bundle-output iOS/main.jsbundle --assets-dest ./ios --sourcemap-output ./iOS/main.jsbundle.min.js.map

Then run this command to upload the sourcemap to Raygun:

curl \
-X POST \
-u "emailaddress:password" \
-F "url=file://reactnative.local/main.jsbundle" \
-F "file=@./ios/main.jsbundle.min.js.map" \
https://app.raygun.io/upload/jssymbols/your_application_id

You will need to update the emailaddress and password to a valid Raygun account. If you don't want to use your account credentials you can create a new account and add it to the Owners team, or a team that has access to the Raygun application.

You will also need to replace your_application_id above with the 6-letter application ID code (available at https://app.raygun.com/dashboard/[app_id]).

When errors are received by Raygun, they will then be source mapped to the unminified code automatically. Every time you finish a version of your app and are about to release it, you should run the above two commands to upload the new source map to Raygun. We do note that this process is quite manual, and is expected to be replaced with an automatic first-class workflow for the production release.

For Android:

1. Optional one-time setup action: ensure there is a directory within your project for the JS bundle, e.g mkdir android/app/src/main/assets

2. Run this command from your project's root directory to build your production app bundle with source maps:

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/main.jsbundle --assets-dest android/app/src/main/res --sourcemap-output android/app/src/main/assets/main.jsbundle.min.js.map

3. Finally, run this command to upload your source map (replacing username, password and your_application_id):

curl \
-X POST \
-u "emailaddress:password" \
-F "url=file://reactnative.local/main.jsbundle" \
-F "file=@./android/app/src/main/assets/main.jsbundle.min.js.map" \
https://app.raygun.io/upload/jssymbols/your_application_id

Note that if you have placed or want to place your jsbundle file in a different location, you can set this location as the value for --sourcemap-output in step 2 and the file=@./ value in the step 3 cURL command.

Python

Documentation - Raygun4Python - Python Error Tracking & Reporting

The Raygun4py provider can send uncaught exceptions by creating a handler and attaching it to sys.excepthook, or automatically by adding the built-in logger. It also supports manual sending from except blocks. It only takes a few minutes to set up so you can start real time error monitoring and crash reporting from your Python applications quickly and easily.

Contents

Setup Instructions

Requirements

Raygun4py is known to work with Python 2.6-2.7, Python 3.1+ and PyPy environments.

It requires the socket module to be built with SSL support.

Installation

Grab the module with pip:

pip install raygun4py

Then include and instantiate it:

from raygun4py import raygunprovider

client = raygunprovider.RaygunSender('your_apikey')

Test the installation

From the command line, run:

$ raygun4py test your_apikey

Replace your_apikey with the one listed on your Raygun dashboard. This will cause a test exception to be generated and sent.

Usage

Automatically send the current exception like this:

try:
    raise Exception("foo")
except:
    client.send_exception()

See sending functions for more ways to send.

Uncaught exception handler

To automatically pick up unhandled exceptions with custom logic, you can provide a callback function to sys.excepthook:

def handle_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 = handle_exception

Logging

You can also send exceptions using a logger:

logger = logging.getLogger("mylogger")
rgHandler = raygunprovider.RaygunHandler("your_apikey")
logger.addHandler(rgHandler)

def log_exception(exc_type, exc_value, exc_traceback):
    logger.error("An exception occurred", exc_info = (exc_type, exc_value, exc_traceback))

sys.excepthook = log_exception

This uses the built-in RaygunHandler. You can provide your own handler implementation based on that class if you need custom sending behavior.

Web frameworks

Raygun4py 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.6/2.7 and Python 3+.

Django

To configure Django to automatically send all exceptions that are raised in views to Raygun:

settings.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,
    'userversion': "Not defined",
    'user': None
}

Flask

from flask import Flask, current_app
from raygun4py.middleware import flask

app = Flask(__name__)

flask.Provider(app, 'your_apikey').attach()

WSGI

An example using Tornado, which will pick up exceptions that occur in the WSGI pipeline:

from raygun4py.middleware import wsgi

class MainHandler(tornado.web.RequestHandler):

  def initialize(self):
      raise Exception('init')

def main():
  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()

Note that many frameworks (tornado, pryramid, gevent et al) will swallow exceptions that occur within their domain.

Attaching raw HTTP request data

If you are in a web server environment and have HTTP request details available, you can pass these and the headers through in a dictionary (see sample.py in the GitHub repository). Code running on Google App Engine is supported - this requires a paid account due to required SSL support.

Public API functions

Initialization options

RaygunSender accepts a config dict which is used to set options on the provider:

from raygun4py import raygunprovider

client = 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,
    'userversion': "Not defined",
    'user': None
})

For the local/global variables, if their options are set to False the corresponding variables will not be sent with exception payloads. http_timeout controls the maximum time the HTTP request can take when POSTing to the Raygun API, and is of type 'float'.

Sending functions

send_exception(exception, exc_info, tags, userCustomData, httpRequest)

  • exception (Exception)
  • exc_info (3-tuple)
  • tags (List)
  • userCustomData (Dict)
  • userCustomData (Dict)

All parameters are optional.

Call this function from within a catch block to send the current exception to Raygun:

# Automatically gets the current exception
httpResult = client.send_exception()

# Uses the supplied sys.exc_info() tuple
httpResult = client.send_exception(exc_info=sys.exc_info())

# Uses a supplied Exception object
httpResult = client.send_exception(exception=exception)

# Send tags, custom data and an HTTP request object
httpResult = client.send_exception(tags=[], userCustomData={}, request={})

You can pass in either of these two exception params:

  • exception should be a subclass of type Exception. Pass this in if you want to manually transmit an exception object to Raygun.
  • exc_info should be the 3-tuple returned from sys.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:

  • tags is a list of tags relating to the current context which you can define.
  • userCustomData is a dict containing custom key-values also of your choosing.
  • httpRequest is HTTP Request data - see sample.py for the expected format of the object.

Config and data functions

filter_keys

Arguments

  • keys (List)

If 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 in the payload will have their value replaced with <filtered> - useful for passwords, credit card data etc. By example:

client.filter_keys(keys=['credit_card', 'cv2', 'password'])

ignore_exceptions

Arguments

  • exceptions (List of strings)

Provide 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.

on_before_send

Arguments

  • callback (Function)

You 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.

on_grouping_key

Arguments

  • callback (Function)

Pass 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).

set_proxy

Arguments

  • host (String)
  • port (Integer)

Call this function if your code is behind a proxy and want Raygun4py to make the HTTP request to the Raygun endpoint through it.

set_version

Arguments

  • version (String)

Call 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.

set_user

Arguments

  • user_info (Dict)

User 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'
  })

Identifier should be whatever unique key you use to identify users, for instance an email address. This will be used to create the count of unique affected users. 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.

Features

Custom grouping logic

You 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:

class MyClass(object):

    def my_callback(self, raygun_message):
        return raygun_message.get_error().message[:100] # Use naive message-based grouping only

    def create_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 exceptions

For Python 3, chained exceptions are now 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.

Local, global and environment variables

Raygun4py can automatically send the names of all variables that are in scope and their values if these options are set. Local variables will send the variable state for each stack frame, and global variables will transmit the state of all variables in global scope. System environment variables are also sent. See Initialization Options above if you wish to disable this.

Troubleshooting

To see the HTTP response code from sending the message to raygun, print client.send() (as in line 27 of test.py). It will be 403 if an invalid API key was entered, and 202 if successful.

Create a thread in the official support forums at http://raygun.com/forums, and we'll help you out.

Raygun4py GitHub Repository

Visit the raygun4py GitHub repository to view the code. Like all our providers, it is available under the MIT license.

macOS

Documentation - Raygun4MacOS - macOS Error & Crash Reporting

Raygun crash reporting and real user monitoring is available for macOS with the Raygun4MacOS provider. The Raygun4MacOS provider can be used in Objective-C and Swift applications. The setup instructions below includes steps to integrate Raygun4MacOS in both types of applications. The features described in these docs also apply to both languages.

Setup instructions (Using CocoaPods)

Raygun can be obtained through CocoaPods which is a macOS (and iOS) dependency manager. Read more about CocoaPods here, or see further below for the manual setup instructions.

1. Update Podfile

Add the following under the relevant target(s) within your project's Podfile:

pod 'Raygun4MacOS'

2. Run pod install

Open a shell, navigate to the location of your project's Podfile and run:

pod install

From now on, make sure to always open the Xcode workspace instead of the project file when building your project.

3. Import dependency

In AppDelegate.m, import the Raygun.h header:

#import <Raygun4MacOS/Raygun.h>

4. Enable the Raygun provider

In the application function of AppDelegate.m, add the following code to enable the Raygun provider. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

[[Raygun sharedReporterWithApiKey:@"YOUR_API_KEY_HERE"] attachPulse];

The steps above will cause all unhandled exceptions and real user monitoring analytics to be sent to your Raygun account.

Setup instructions (Manual)

If you don't use CocoaPods, follow these instructions to manually download and reference the Raygun4MacOS framework.

1. Download Raygun4MacOS

Download and unzip the current version from here: Raygun4MacOS Version 1.0.2

2. Reference Raygun4MacOS in your project

In Xcode, click on your project and then select your main app target. Go to the "Build Phases" tab and expand "Link Binary With Libraries". Drag Raygun4MacOS.framework into the library list.

3. Import dependency

In AppDelegate.m, import the Raygun.h header:

#import <Raygun4MacOS/Raygun.h>

4. Enable the Raygun provider

In the application function of AppDelegate.m, add the following code to enable the Raygun provider. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

[[Raygun sharedReporterWithApiKey:@"YOUR_API_KEY_HERE"] attachPulse];

Setup instructions (Swift)

Swift is another langauge created by Apple for building Mac (and iOS) applications. The same Raygun4MacOS provider mentioned above for Objective-C Mac applications can also be used in Swift Mac apps.

  1. Installation - same as with Objective-C applications, there are two ways to install Raygun4MacOS into your Swift Mac app: via the CocoaPods dependancy manager, or by manually downloading and referencing the library. The CocoaPods instructions and the download link can be found above.
  2. Once your application is referencing the Raygun4MacOS library, import Raygun4MacOS into the bridging-header file of your Swift app:
    #import <Raygun4MacOS/Raygun4MacOS.h>
  3. Finally, in AppDelegate.swift, add the following code to the application function:
    [Raygun .sharedReporterWithApiKey("YOUR_APP_API_KEY")]

Unique user tracking

Raygun supports tracking the unique users who encounter bugs in your apps. You can transmit the current user who was affected by the exception by calling the identify method on the current raygun client (code example below). You pass a string to this method to represent the user which could be a database id, username, email address or whatever works for you. A count of affected users will then appear in the error statistics in Raygun. If you provide an email address, you will see it on the error page in Raygun, and if they have an associated Gravatar you will see that too. If the user context changes, for instance on log in/out, you should remember to call identify again to store the updated identity. This feature is optional if you wish it disabled for privacy purposes. Below is an example of setting the user identity after the usual Raygun4MacOS initialization.

[[Raygun sharedReporter] identify:@"UNIQUE_USER_IDENTITY"];

Symbolication

The macOS provider transmits encoded crash reports it receives from your app as it runs on devices or emulators. To turn these crash reports into useful data that you can use to debug, Raygun requires your app's dSYM file. This is generated on build in Xcode and is unique to every version of your app's source. When you are finished testing locally and are deploying a new build, you need to upload the new dSYM file corresponding to that build.

Once Raygun has that build's dSYM file, the encoded crash reports will be turned into complete back traces, with line numbers and file names.

Uploading a dSYM file

Here are 3 options for uploading your dSYM files to your Raygun account:

Native dSYM uploading app - Raygun Sidekick

The Raygun Sidekick is a native Mac application that sits in your Mac menu bar which will detect, zip and upload the appropriate dSYM file in just a few clicks. It is highly recommend that you use the Raygun Sidekick rather than tediously uploading the dSYM files yourself as described below.

Download the Raygun Sidekick right here and check out the documentation for more info.

Manual upload

To manually upload dSYM files, visit the Raygun dashboard, click on dSYM Center in the sidebar, then upload the dSYM file by drag 'n dropping or using Finder.

You can do this at any time. If you deploy a new build and Raygun receives crash reports without the dSYM file, it will store them ready for you to upload it. When you do, visit an error from that build and click on 'Reprocess crash report'. After a short delay, the stack trace will appear.

Manual uploading via cURL

For sending dSYMs to Raygun in other processes such as build scripts or the terminal, you can post via cURL:

curl -H "Host: app.raygun.io" -H "Authorization: Basic <token>" --form "DsymFile=@build/${APP_NAME}-${BUILD_NUMBER}-dSYM.zip" https://app.raygun.io/dashboard/${APP_ID}/settings/symbols

where APP_NAME and BUILD_NUMBER make up the name of the zippped dSYM. The APP_ID is available in the URL of your app in the Raygun dashboard.

<token> should be replaced with a basic auth token which can be created by Base64 encoding your Raygun account credentials in the following format (make sure not to forget the colon between them): username:password

Pulse

The setup instructions above will enable both Crash Reporting as well as Pulse, which logs Real User Monitoring analytics to your Raygun application dashboard. This information includes when your app starts and stops, which views your users navigate through, network calls that your app makes and any user details that you have provided.

Pulse messages will be sent to Raygun as soon as the app starts up. So once you've set up Raygun in your app, run it up and go to your Raygun Pulse dashboard to see the data it collects. Of course Pulse is most valuable once your app is out there being used by your users.

Network calls

Once enabled, Raygun4MacOS will automatically log the performance of network calls made with the following methods.

  • [NSURLSession dataTaskWithURL:]
  • [NSURLSession dataTaskWithURL:completionHandler:]
  • [NSURLSession dataTaskWithRequest:]
  • [NSURLSession dataTaskWithRequest:completionHandler:]
  • [NSURLSession downloadTaskWithURL:]
  • [NSURLSession downloadTaskWithURL:completionHandler:]
  • [NSURLSession downloadTaskWithRequest:]
  • [NSURLSession downloadTaskWithRequest:completionHandler:]
  • [NSURLSession uploadTaskWithRequest:fromData:]
  • [NSURLSession uploadTaskWithRequest:fromData:completionHandler:]
  • [NSURLSession uploadTaskWithRequest:fromFile:]
  • [NSURLSession uploadTaskWithRequest:fromFile:completionHandler:]
  • [NSURLConnection sendAsynchronousRequest:queue:completionHandler]
  • [NSURLConnection sendSynchronousRequest:returningResponse:error:]

Details about logged network calls can be found on the Performance tab of your Pulse dashboard.

Nancy

Documentation - Raygun4Nancy - Nancy Error & Crash Reporting

Nancy.Raygun is an easy to install third party provider for Raygun that gives you fast access to Raygun crash reporting and error monitoring.

Installing Nancy.Raygun

Using Nuget, install the Nancy.Raygun package.

PM> Install-Package Nancy.Raygun

Configuring Raygun

RaygunSettings

In your Web.config file, find configSections and add the following entry:

<configSections>
  <section name="RaygunSettings" type="Nancy.Raygun.RaygunSettings, Nancy.Raygun" />
</configSections>

Then reference it by adding the following line somewhere after the configSections tag. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

<RaygunSettings apikey="YOUR_APP_API_KEY" />

appSettings

If you're hosting on Azure/AppHabor then you may want to use appSettings instead so you can add the key via the portal/administration area.

To do this, add a the key nr.apiKey to your appSettings, with the value being your API key.

<appSettings>
  <add key="nr.apiKey" value="YOUR_APP_API_KEY" />
</appSettings>

That's it, now all your errors will get Zapped by Raygun. Don't let Robby down, he wants your errors!

To view the source for Nancy.Raygun visit the GitHub page here: https://github.com/phillip-haydon/Nancy.Raygun

Node.js

Documentation - Raygun4Node - Node.js Error Tracking & Reporting

The raygun4node provider

The official Raygun provider for node.js allows you to easily access crash reporting and error monitoring for your node.js network application.

This provider is flexible and supports many configuration scenarios - you can have it running and sending errors quickly, by manually placing send() calls when you detect an error. If you are using the Express.js web application framework, you can add the included middleware at the end of your middleware definitions. Or, you can use node.js domains.

The provider is available at the Raygun4node GitHub repository.

What can I send from my node.js application?

The provider can send Error objects, with error details (time, message etc) a stack trace, request data, environment data, custom user data and more. If you wish to manually send other information, the transport object has a Send function which will pass data to Raygun with the required fields.

Getting started

To add Raygun to your node.js app, follow these steps:

  1. In your project root, grab the module by running
    npm install raygun
  2. Create a RaygunClient using your application API key:

    var raygun = require('raygun');
    var raygunClient = new raygun.Client().init({ apiKey: '{{yourApiKey}}' });

Sending errors

Using domains

A good way to trap and send exceptions, as it works with both synchronous and asynchronous code, is by using domains. In the code sample below, a test error is being thrown in the run function.

var d = require('domain').create();

setTimeout(function () {
  process.exit(1);
}, 3000).unref();

raygunClient.send(err, null, function () {
  process.exit(1);
});

d.run(function(){
  var err = new Error('phasers offline');
  throw err;
});

Express.js

If you are using express.js to develop a web application, you can use the provided middleware as an error handler, at the bottom of your middleware definitions:

var raygunClient = new raygun.Client().init({apiKey: '{{yourApiKey}}'});

...
app.use(express.static(path.join(__dirname, 'public')));
app.use(raygunClient.expressHandler);
var err = new Error('help!');
throw err;

Other NodeJS frameworks

We have written a quick start blog post that covers Hapi, Restify, Koa and pure Node HTTP.

Manual sending

If you don't want to use domains, such as with in an older version of node.js, you can also wrap your code in a try block, then call raygunClient.send(err) in the catch block.

Error tracking examples

We've created a blog post showing ways to send errors in node.js to Raygun - check it out for idiomatic examples of how to set up the provider. Often the most appropriate way is to use Domains, or the included Express middleware handler if you use express.js.

Sending custom data

You can pass custom data in on the Send() function, as the second parameter. For instance:

client.send(new Error(), { 'mykey': 'beta' }, function (response){ });

Callback

client.send(new Error(), {}, function (response){ });

The value passed to the 3rd argument callback is the response from the Raygun API - there's nothing in the body, it's just a status code response. If everything went ok, you'll get a 202 response code. Otherwise we throw 401 for incorrect API keys, 403 if you're over your plan limits, or anything in the 500+ range for internal errors. We use the nodejs http/https library to make the POST to Raygun, you can see more documentation about that callback here:https://nodejs.org/api/http.html#http_http_request_options_callback

Sending request data

You can send the request data in the Send() function, as the fourth parameter. For example:

client.send(new Error(), {}, function () {}, request);

If you want to filter any of the request data then you can pass in an array of keys to filter when you init the client. For example:

var raygun = require('raygun');
var raygunClient = new raygun.Client().init({ apiKey: 'your API key', filters: ['password', 'creditcard'] });

Tags

You can add tags to your error in the Send() function, as the fifth parameter. For example:

client.send(new Error(), {}, function () {}, {}, ['custom tag 1', 'important error']);

Unique user tracking

You can set raygunClient.user to a function that returns the user name or email address of the currently logged in user. An example, using the Passport.js middleware:

var raygunClient = new raygun.Client().init({apiKey: "yourkey"});

raygunClient.user = function (req) {
  if (req.user) {
    return req.user.username;
  }
}

Version tracking

Call setVersion(string) on a RaygunClient to set the version of the calling application. This is expected to be of the format x.x.x.x, where x is a positive integer. The version will be visible in the dashboard.

Source maps

Raygun supports source mapping for Node.js stacktraces which include column numbers. To enable this feature you will need to upload your map files to the JavaScript Source Map Center and enable the processing of Node.js error stacktraces. See the source maps documentation for more information on this.

PHP

Documentation - Raygun4PHP - PHP Error Tracking & Reporting

The Raygun4PHP provider

Raygun4PHP is a library that you can easily add to your PHP-based website, which will then allow you to transmit all errors and exceptions to your Raygun Crash Reporting dashboard. Installation is painless, and configuring your site to start real time error monitoring and crash reporting takes only 5 minutes.

Raygun4PHP only requires that the server has PHP5.3 (or greater) and curl installed. The package manager Composer is optional, but if it is available installation is simple.

What can I send to Raygun Crash Reporting?

Raygun4PHP is designed to send both classical PHP errors, as well as PHP5 exception objects. Send() functions are available for both of these, that call a Send() that takes an ErrorException, which is also publically available. You can add a set of tags (as an array of strings) to identify a certain type of message, or add a custom user data (as an associative array). Dedicated functions for sending messages to Raygun instead of errors or exceptions are coming soon.

Lightning-quick asynchronous error sending

For supported platforms (*nix, OS X, some Windows) the PHP provider has fully asynchronous, non-blocking sending logic. This ensures the user recieves the requested page without having to wait for the server to send its error message to Raygun. Many of our competitors post their messages in a blocking way, leading to slow load times for the user. With Raygun your site remains highly responsive while it transmits error data.

Installation

Firstly, ensure that curl is installed and enabled in your server's php.ini file.

With Composer

Composer is a package management tool for PHP which automatically fetches dependencies and also supports autoloading - this is a low-impact way to get Raygun4php into your site.

  1. If you use a *nix environment, follow the instructions to install Composer. Windows users can run this installer to automatically add it to the path etc.
  2. Inside your project's root directory create a composer.json file, containing:

    {
        "require": {
            "mindscape/raygun4php": "1.*"
        }
    }
  3. From your shell run php composer.phar install (*nix) or composer install (Windows). This will download Raygun4Php and create the appropriate autoload data.
  4. Then in a PHP file just add this, and the library will be ready for use:

    require_once 'vendor/autoload.php';

Manually with Git

Clone this repository and copy src/Raygun4php into an appropriate subdirectory in your project, such as /vendor/Raygun4php. Add requires definitions for RaygunClient.php where you want to make a call to Send().

require (dirname(dirname(__FILE__)).'/vendor/Raygun4php/RaygunClient.php');

Usage

You can send both PHP errors and object-oriented exceptions to Raygun. An easy way to accomplish this is to create a file containing exception and error handlers which make calls to the appropriate Raygun4php functions. As above, import Raygun4php - if you're using Composer, just add require_once 'vendor/autoload.php', or if not manually import RaygunClient.php. Then, create handlers that look like this:

namespace
{
    // paste your 'requires' statement

    $client = new \Raygun4php\RaygunClient("apikey for your application");

    function error_handler($errno, $errstr, $errfile, $errline ) {
        global $client;
        $client->SendError($errno, $errstr, $errfile, $errline);
    }

    function exception_handler($exception)
    {
        global $client;
        $client->SendException($exception);
    }

    set_exception_handler('exception_handler');
    set_error_handler("error_handler");
}

Note that if you are placing in inside a file with a namespace of your choosing, the above code should be declared to be within the global namespace (thus the namespace { } is required). You will also need whichever requires statement as above (autoload or manual) before the $client instantiation. Copy your application's API key from the Raygun Crash Reporting dashboard, and place it in the constructor call as above (do not include the curly brackets). If the handlers reside in their own file, just import it in every file where you'd like exceptions and errors to be sent, and they will be delivered to Raygun Crash Reporting.

Manually sending exceptions

You can manually send exceptions at any time with the stack trace like this:

require_once "vendor/autoload.php"; // if using Composer

$client = new \Raygun4php\RaygunClient("apikey");
try {
  throw new Exception("Your message");
} catch (Exception $e) {
  $client->SendException($e);
}

Sending method - async/sync

Raygun4PHP has two algorithms which it can use to send your errors:

  • Asynchronous: POSTs the message and returns to your script immediately without waiting for the response from the Raygun API.

  • Synchronous: POSTs the message, blocks and receives the HTTP response from the Raygun API. This uses a socket connection which is still reasonably fast. This also allows the use of the debug mode to receive the HTTP response code; see below.

This can be set by passing in a boolean as the 2nd parameter to the constructor:

$client = new \Raygun4php\RaygunClient("apiKey", $useAsyncSending);

$useAsyncSending options

Type: boolean Linux/OS X default: true Windows default: false

  • If $useAsyncSending is true, and the script is running on a *nix platform, the message will be delivered asynchronously. SendError() and SendException() will return 0 if all went well

  • If $useAsyncSending is false, the script will block and receive the HTTP response.

For Windows, false is the only effective option available due to limitations of arguments passed to CLI cURL. This may be revisited in the future.

HTTP Proxy

You can make Raygun4PHP post through an HTTP proxy of your choice like this:

$client->setProxy('http://myproxy:3128');

Debug mode

New in 1.3, the client offers a debug mode in which the HTTP response code can be returned after a POST attempt. This can be useful when adding Raygun to your site. This is accessed by passing in true as the third parameter in the client constructor:

$client = new \Raygun4php\RaygunClient("apiKey", $useAsyncSending, $debugMode);

$debugMode options

Default: false If true is passed in, and $useAsyncSending is set to false, client->SendException() or SendError() will return the HTTP status code of the POST attempt. Note: If $useAsyncSending is true, $debugMode is not available.

Response codes

202: Message received by Raygun API correctly

403: Invalid API key. Copy it from your Raygun Application Settings, it should be of the form new RaygunClient("A+nUc2dLh27vbh8abls7==")

400: Bad message. This may indicate an invalid payload - please contact us if you continue to see this.

Version numbers

You can transmit the version number of your PHP project along with the message by calling SetVersion() on your RaygunClient after it is instantiated - this is optional but recommended as the version number is considered to be first-class data for a message.

Adding Tags

Tags can be added to error data to provide extra information and to help filtering errors within Raygun. They are provided as an array of strings or numbers passed as the 5th argument to the SendError function and as the 2nd argument to the SendException function.

The declaration of the exception and error handlers using tags could look something like this:

$tags = array("testing-enviroment", "machine-4");

function error_handler($errno, $errstr, $errfile, $errline) {
    global $client, $tags;
    $client->SendError($errno, $errstr, $errfile, $errline, $tags);
}

function exception_handler($exception) {
    global $client, $tags;
    $client->SendException($exception, $tags);
}

User tracking

You can call $client->SetUser($user), passing in a string representing the username or email address of the current user of the calling application. This will be attached to the message and visible in the dashboard. This method is optional - if it is not called, a random identifier will be used. If you use this, and the user changes (log in/out), be sure to call it again passing in the new user (or just call $client->SetUser() to assign a new random identifier). Note that this data is stored as a cookie. If you do not call SetUser the default is to store a random UUID to represent the user. This feature can be used in CLI mode by calling SetUser(string) at the start of your session.

Sensitive data filtering

Some error data will be too sensitive to transmit to an external service, such as credit card details or passwords. Since this data is very application specific, Raygun doesn't filter out anything by default. You can configure to either replace or otherwise transform specific values based on their keys. These transformations apply to form data ($_POST), custom user data, HTTP headers, and environment data ($_SERVER). It does not filter the URL or its $_GET parameters, or custom message strings. Since Raygun doesn't log method arguments in stack traces, those don't need filtering. All key comparisons are case insensitive.

$client = new \Raygun4php\RaygunClient("apiKey");
$client->setFilterParams(array(
    'password' => true,
    'creditcardnumber' => true,
    'ccv' => true,
    'php_auth_pw' => true, // filters basic auth from $_SERVER
));
// Example input: array('Username' => 'myuser','Password' => 'secret')
// Example output: array('Username' => 'myuser','Password' => '[filtered]')

You can also define keys as regular expressions:

$client = new \Raygun4php\RaygunClient("apiKey");
$client->setFilterParams(array(
    '/^credit/i' => true,
));
// Example input: array('CreditCardNumber' => '4111111111111111','CreditCardCcv' => '123')
// Example output: array('CreditCardNumber' => '[filtered]','CreditCardCcv' => '[filtered]')

In case you want to retain some hints on the data rather than removing it completely, you can also apply custom transformations through PHP's anonymous functions. The following example truncates all keys starting with "address".

$client = new \Raygun4php\RaygunClient("apiKey");
$client->setFilterParams(array(
    'Email' => function($key, $val) {return substr($val, 0, 5) . '...';}
));
// Example input: array('Email' => 'test@test.com')
// Example output: array('Email' => 'test@...')

Note that when any filters are defined, the Raygun error will no longer contain the raw HTTP data, since there's no effective way to filter it.

Troubleshooting

As above, enable debug mode by instantiating the client with

$client = new \Raygun4php\RaygunClient("apiKey", FALSE, TRUE);

This will echo the HTTP response code. Check the list above, and create an issue or contact us if you continue to have problems.

Raygun4PHP GitHub Repository

For complete installation instructions, getting the source code and troubleshooting, visit the GitHub repository here.

Ruby on Rails

Documentation - Raygun4Ruby - Ruby on Rails Error Monitoring & Reporting

The Raygun4Ruby provider

This is the official provider for the Ruby ecosystem - it also has built-in support for Rails.

Why add Raygun to my Ruby app?

Ruby is a great, flexible language that allows you to write powerful applications, whether for the web with a framework or elsewhere. All software has bugs; a good developer recognizes this and the fact that the correct tools can help minimize their effect. Specifically, the effect on his or her users. Raygun allows your app to automatically send real time error and crash reports, and place them on a dashboard, allowing you to easily diagnose and fix the issue.

Raygun4Ruby Features

This provider has first-class support for:

  1. Ruby 1.9 or greater
  2. Rails 3/4/5

It also includes a Resque failure backend, for notifying Raygun if its queue falls over.

Installation

It comes as a gem, so add this line to your application's Gemfile':

gem 'raygun4ruby'

And then execute:

bundle

Or install it yourself using:

gem install raygun4ruby

rails

rails g raygun:install your_api_key

You can find your API key on your Raygun Dashboard

You can then test your Raygun integration by running:

rake raygun:test

You should see an "ItWorksException" appear in your Raygun dashboard. You're ready to zap those errors!

Note that the generator will create a file in config/initializers called "raygun.rb". If you need to do any further configuration or customization of Raygun, that's the place to do it!

By default the Rails integration is set to only report Exceptions in Production. To change this behaviour, set config.enable_reporting to something else in config/initializers/raygun.rb.

Rails 2

Raygun4Ruby doesn't currently support Rails 2. If you'd like Rails 2 support, drop us a line.

Sinatra

To enable exception tracking in Sinatra, just add configure Raygun and use the Rack middleware in your app:

require 'raygun4ruby'
Raygun.setup do |config|
  config.api_key = "YOUR_API_KEY_HERE"
end
use Raygun::Middleware::RackExceptionInterceptor

Feature Overview

Manual exception tracking

With vanilla Ruby, it's easy as:

require 'rubygems'
require 'raygun4ruby'

Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_parameters = [ :password, :card_number, :cvv ] # don't forget to filter out sensitive parameters
  config.enable_reporting = true # to send errors, false to not log
end

begin
  # your lovely code here
rescue Exception => e
  Raygun.track_exception(e)
end

You can also pass a Hash as the second parameter to track_exception. It should look like a Rack Env Hash

Custom User Data

Custom data can be added to track_exception by passing a custom_data key in the second parameter hash.  

begin
  # more lovely code
rescue Exception => e
  Raygun.track_exception(e, custom_data: {my: 'custom data', goes: 'here'})
end

This data is filtered by default using the options set in Rails.application.config.filter_parameters.  To setup additional keys please see the section below titled Sensitive POST data filtering.

Ignoring Some Errors

You can ignore certain types of Exception using the ignore option in the setup block, like so:

Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.ignore  << ['MyApp::AnExceptionIDontCareAbout']
end

The following exceptions are igonored by default:

ActiveRecord::RecordNotFound
ActionController::RoutingError
ActionController::InvalidAuthenticityToken
ActionDispatch::ParamsParser::ParseError
CGI::Session::CookieStore::TamperedWithCookie
ActionController::UnknownAction
AbstractController::ActionNotFound
Mongoid::Errors::DocumentNotFound

You can see this here and unignore them if needed by doing the following:

Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.ignore.delete('ActionController::InvalidAuthenticityToken')
end

Using a Proxy

You can pass proxy settings using the proxy_settings config option.

Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.proxy_settings = { host: "localhost", port: 8888 }
end

Sensitive POST data filtering

The provider can automatically remove data you don't want transmitted, such as passwords or credit card info. This defaults to Rails.application.config.filter_parameters, but you can specify additional keys like this:

Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_parameters = [ :password, :card_number, :cvv ]
end

This filtering also applies to information submitted through the custom user data mentioned previously.

Customizing Parameter Filtering

If you'd like to customize how parameters are filtered, you can pass a Proc to filter_parameters. Raygun4Ruby will yield the params hash to the block, and the return value will be sent along with your error.

Raygun.setup do |config|
  config.api_key = "YOUR_RAYGUN_API_KEY"
  config.filter_parameters do |params|
    params.slice("only", "a", "few", "keys") # note that Hash#slice is in ActiveSupport
  end
end

Affected User Tracking

Raygun can now track how many users have been affected by an error.

By default, Raygun looks for a method called current_user on your controller, and calls either emailusername or id on the object returned by that method.

You can customize those method names in your configuration block:

Raygun.setup do |config|
  config.api_key = "MY_SWEET_API_KEY"
  config.affected_user_method = :my_current_user # `current_user` by default
  config.affected_user_identifier_methods << :login # `[ :email, :username, :id ]` by default - will use the first that works
end

If you're using Rails, most authentication systems will have this method set and you should be good to go.

The count of unique affected users will appear on the error group in the Raygun dashboard. If your user has an email method, and that email has a Gravatars associated, you will also see your user's avatar.

If you wish to keep it anonymous, you could set this identifier to something like SecureRandom.uuid and store that in a cookie, like so:

class ApplicationController < ActionController::Base

  def raygun_user
    cookies.permanent[:raygun_user_identifier] ||= SecureRandom.uuid
  end

end

(Remember to set affected_user_method to :raygun_user in your config block...)

Version tracking

Raygun can attach the version of your application to its error reports. In your Raygun.setup block, set version to the current version of your app.

Raygun.setup do |config|
  config.version = "1.0.0.4" # you could also pull this from ENV or however you want to set it.
end

Tags

Raygun allows you to tag error reports with any number of tags. In your Raygun.setup block, set tags to an array of strings to have those set on any error reports sent by the gem.

Raygun.setup do |config|
  config.tags = ['heroku']
end

Resque Error Tracking

Raygun4Ruby also includes a Resque failure backend. You should include it inside your Resque initializer (usually something like config/initializers/load_resque.rb)

require 'resque/failure/multiple'
require 'resque/failure/raygun'
require 'resque/failure/redis'

Resque::Failure::Multiple.classes = [Resque::Failure::Redis, Resque::Failure::Raygun]
Resque::Failure.backend = Resque::Failure::Multiple

Sidekiq Error Tracking

Raygun4Ruby can track errors from Sidekiq (2.x or 3+). All you need to do is add the line:

  require 'raygun/sidekiq'

Either in your Raygun initializer or wherever else takes your fancy :)

Raygun4Ruby GitHub Repository

Visit the Raygun4Ruby Github repository to view the code.

Unity

Documentation - Raygun4Unity - Unity Error Monitoring & Crash Reporting

Raygun4unity allows you to setup real time error monitoring and crash reporting for your Unity games.  

Setup instructions

1. Download the library

Download raygun4Unity.zip from the latest release listed on Github. Extract the contents and paste the raygun4Unity folder somwhere into the Assets directory of your game.

2. Listen to RegisterLogCallback

If you haven't done so already, listen to Application.RegisterLogCallback in a C# script. Attach this script to a GameObject that will be used when your game is loaded.

3. Use the RaygunClient to send exception reports

In your RegisterLogCallback handler (or any part of your game that listens to unhandled exceptions), create an instance of the RaygunClient by passing your API key into the constructor, then call one of the Send methods. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings.

public class Logger : MonoBehaviour
{
  void Start ()
  {
    Application.RegisterLogCallback(HandleException);
  }

  private void HandleException(string message, string stackTrace, LogType type)
  {
    if (type == LogType.Exception || type == LogType.Error)
    {
      RaygunClient raygunClient = new RaygunClient("OIxvu7YKU4erOuQ791Q4HQ==");
      raygunClient.Send(message, stackTrace);
    }
  }
}

WARNING RegisterLogCallback can only have one handler at a time, so if you already are using RegisterLogCallback, then you'll want to send the exception information to Raygun.io within your existing callback.

Unique user tracking

To keep track of how many users are affected by each exception, you can set the User or UserInfo property of the RaygunClient instance. The user can be any id string of your choosing to identify each user. Ideally, try to use an id that you can use to relate back to an actual user such as a database id, or an email address. If you use an email address, the users gravitars (if found) will be displayed on the Raygun.io error dashboards. Below is an example of setting the User property:

raygunClient.User = "user@email.com";

The UserInfo property lets you provide additional user information such as their name:

raygunClient.UserInfo = new RaygunIdentifierMessage("user@email.com")
{
  IsAnonymous = false,
  FullName = "Robbie Robot",
  FirstName = "Robbie"
};

Here are all the available RaygunIdentifierMessage properties. The only required field is Identifier.

  • Identifier is the unique identifier from your system for this user.
  • IsAnonymous is a flag indicating whether the user is logged in (or identifiable) or if they are anonymous. An anonymous user can still have a unique identifier.
  • Email The user's email address. If you use email addresses to identify your users, feel free to set the identifier to their email and leave this blank, as we will use the identifier as the email address if it looks like one, and no email address is not specified.
  • FullName The user's full name.
  • FirstName The user's first (or preferred) name.
  • UUID A device identifier. Could be used to identify users across devices, or machines that are breaking for many users.

Tags and custom data

A couple of Send method overloads allow you to attach a list of tags and a dictionary of key-value custom data to the exception report. Tags and custom data get displayed on each report in Raygun. Either of these can be null if you only want to send one or the other.

The following overload is for when sending the message and stacktrace strings as provided by Unity in the HandleException callback.

var tags = new List() { "Level 6", "0 lives"};
var customData = new Dictionary() { {"Difficulty", "Very-Hard"} };
raygunClient.Send(message, stacktrace, tags, customData);

Another overload is available for when sending a .NET Exception object.

var tags = new List() { "Level 6", "0 lives"};
var customData = new Dictionary() { {"Difficulty", "Very-Hard"} };
raygunClient.Send(exception, tags, customData);

Game version

The current version of raygun4Unity does not automatically obtain the game version number. You can however specify this by setting the ApplicationVersion property of the RaygunClient instance.

raygunClient.ApplicationVersion = "1.3.37.0";

WordPress

Documentation - Raygun4WordPress - Wordpress Error Reporting

Raygun4WP plugin allows you to easily setup Crash Reporting and Real User Monitoring on Wordpress website without you having to write a single line of code.

Dependancies

This plugin utilizes lower-level Raygun providers to add this functionality:

  • Raygun4PHP: Server-side error tracking
  • Raygun4JS: Client-side error tracking and real user monitoring

Requirements

The following server requirements are needed in order to use this plugin.

  • PHP 5.3.3+
  • Curl Installed

If you are using a *nix system, the package php5-curl may contain the required dependencies.

Contents

Installation

Manually with Git

Clone the repository into your Wordpress installation's /plugins folder - for instance at /wordpress/wp-content/plugins.

Make sure you use the --recursive flag to also pull down the Raygun4PHP and Raygun4JS dependancies.

git clone --recursive https://github.com/MindscapeHQ/raygun4wordpress.git

From Wordpress plugin directory

You can also add Raygun4WP plugin repository using your admin panel.  Raygun4WP is available on wordpress.org/plugins/raygun4wp/.

Usage

  • Navigate to your Wordpress admin panel, click on Plugins, and then Activate Raygun4WP
  • Go to the Raygun4WP settings panel either by the sidebar or admin notification
  • Copy your application's API key from the Raygun dashboard and place it in the API key field.
  • Enable Error Tracking (both server-side and client-side), Real User Monitoring and any other options
  • Save your changes
  • Done!

Pulse - Real User Monitoring

As of 1.8 of Raygun4WP plugin you can enable real user monitoring.

This feature can be enabled via the Settings page under Pulse - Real User Monitoring.

User information will be sent along if you have the unique user tracking feature enabled.

Client-side error tracking

Since 1.4 of the Raygun4WP plugin you can enable client-side error monitoring.

This feature automatically tracks JavaScript errors that occur in your user's browsers when they are loaded.

Raygun for wordpress crash reporting settings

This setting can be activated via the Settings page.

User tracking

This feature can be enabled via the Settings page. 

Enabling this feature will send through the currently logged in user's email address, first name and last name with each message to Raygun. This applies to both Crash Reporting and Pulse payloads. 

If a user is not logged in, no user data will be sent and a random ID will be assigned to the user. 

The user's information will then be available to you when viewing crash reports and user sessions. If the user has an associated Gravatar with that address, you will see their picture. 

If this feature is not enabled, a random ID will be assigned to each user.

Tagging errors

Since 1.8 both client-side and server-side errors can be tagged. Tags are custom test allowing you to easily identify errors.

JavaScript and PHP errors can be tagged independently through a comma-delimited list in the field on the settings page.   

Raygun for wordpress error tagging

For example: Error, JavaScript would add two tags. The first being Error second one being JavaScript

Ignored domains

Domains to ignore for crash reporting and pulse

You can enter a comma-delimited list in the field on the Config page to prevent certain domains from sending errors and from being tracked with real user monitoring.

Async sending

Introduced in 1.1.3, this provider will now send asynchronously on *nix servers (async sockets) resulting in a massive speedup - POSTing to Raygun now takes ~56ms including SSL handshakes. This behaviour can be disabled in code if desired to fall back to blocking socket sends. Async sending is also unavailable on Windows due to a bug in PHP 5.3, and as a result it uses cURL processes. This can be disabled if your server is running a newer environment; please create an issue if you'd like help with this.

Multisite support

It is recommended to use the most recent version WordPress and PHP possible. This procedure should be first followed on a staging server that matches your production environment as closely as possible, then replicated live.

  1. On your root network site, install the plugin using the Admin dashboard's Plugin page as standard, but do not activate it.
  2. FTP in and modify wp-content/plugins/raygun4wp/raygun4wp.php - change the value on line 12 totrue.
  3. Visit the Admin dashboard of a child site (not the root network site). Go to its Plugin page, and you should see raygun4WP ready to be activated - do so.
  4. A new raygun4WP submenu will be added to the left. In there click on Configuration, paste in your API key, change the top dropdown to Enabled then click Save Changes. You can now click Send Test Error and one will appear in your dashboard.
  5. Repeat the above process for any other child sites - you can use different API keys (to send to different Raygun apps) or the same one.

Finally, if you so desire you should be able to visit the root network site, activate it there and configure it. You must however activate it on at least one child site first.

 

Documentation missing?

If we don't have documentation about your desired topic, send us a message and we'll create it for you.