Configuration options

The Bugsnag client object has several properties which can be set to customize the content of error reports and how the reports are sent.

Most configuration options can be specified by initialising Bugsnag and then calling the relevant set method:

Bugsnag.init(this);
Bugsnag.setAppVersion("1.0.0-alpha");

or by creating a Configuration object and passing it into Bugsnag.init:

Configuration config = new Configuration("your-api-key-here");
config.setAppVersion("1.0.0-alpha");
Bugsnag.init(this, config);

Some options must be set during initialization using the Configuration object because they affect the way that Bugsnag is initialized.

To set different configuration values based on build variants or product flavors, see Customizing by build setting.

automaticallyCollectBreadcrumbs

By default we will automatically add breadcrumbs for common application events such as activity lifecycle events and system intents. To disable this behavior, set this property to false:

config.setAutomaticallyCollectBreadcrumbs(false);

beforeNotify

Add a callback to be executed code before every notification to Bugsnag.

You can use this to add or modify information attached to an error before it is sent to your dashboard. You can also return false from any callback to halt execution.

Bugsnag.beforeNotify(new BeforeNotify() {
    @Override
    public boolean run(Error error) {
        error.setSeverity(Severity.INFO);
        return true;
    }
});

See the customizing error reports) reference for more information.

disableExceptionHandler

By default, Bugsnag reports unhandled exceptions in your application automatically. To disable this behavior, call disableExceptionHandler:

Bugsnag.disableExceptionHandler();

setAppVersion

We’ll automatically pull your app version from the versionName field in your AndroidManifest.xml file. If you’d like to override this you can call setAppVersion:

Bugsnag.setAppVersion("1.0.0-alpha");

setAutoCaptureSessions

Set to true if you would like Bugsnag to automatically capture sessions.

Bugsnag.setAutoCaptureSessions(true);

Using this option, Bugsnag will report a session each time:

  • An Activity is in the Started state, 30 seconds after all Activities have remained in the Stopped state.

setContext

Bugsnag uses the concept of “contexts” to help display and group your errors. Contexts represent what was happening in your application at the time an error occurs. In an android app the “context” is automatically set as the foreground Activity.

If you would like to set this value manually, you can call setContext:

Bugsnag.setContext("SecondTutorialStep");

If your bugsnag-android version is older than 4.3.2, it is necessary to add the GET_TASKS permission to your manifest to enable automatic context tracking.

setEndpoint

Set the endpoint to which error reports are sent. By default, reports are sent to https://notify.bugsnag.com endpoint, but this option should be overridden if you are using Bugsnag On-premise, to point to your own Bugsnag endpoint:

Configuration config = new Configuration("your-api-key-here");
config.setEndpoint("https://bugsnag.internal.example.com");
Bugsnag.init(this, config);

setErrorReportApiClient

Sets the ErrorReportApiClient implementation used to make network calls to the Error Reporting API. This may be useful if you have requirements such as certificate pinning and rotation, which are not supported by the default implementation.

Bugsnag.setErrorReportApiClient(new CertPinnedApiClient());

Implementations of ErrorReportApiClient must throw a BadResponseException if the response code is not 200, and a NetworkException if the request could not be completed. The request body must match the structure specified in the Error Reporting API documentation.

An example of a custom client which uses certificate pinning is provided below.

/**
 * A custom API client which uses Square's OkHttp3 Library to pin certificates.
 */
class CertPinnedApiClient implements ErrorReportApiClient {
    OkHttpClient okHttpClient;

    // The public key hash(es) for your cert
    // can be found by following OkHttp3 instructions:
    // https://square.github.io/okhttp/3.x/okhttp/okhttp3/CertificatePinner.html
    CertPinnedApiClient() {
        String hash1 = "sha256/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX="
        String hash2 = "sha256/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX="

        CertificatePinner certificatePinner = new CertificatePinner.Builder()
            .add("mywebsite.com", hash1) // expires in 2019
            .add("mywebsite.com", hash2) // expires in 2020
            .build();

        okHttpClient = new OkHttpClient.Builder()
            .certificatePinner(certificatePinner)
            .build();
    }

    String getReportJson(Report report) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JsonStream jsonStream = new JsonStream(new PrintWriter(baos));
            report.toStream(jsonStream);
            jsonStream.flush();
            return baos.toString("UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("Failed to generate request", e);
        }
    }

    @Override
    public void postReport(String urlString,
                           Report report
                           Map<String, String> headers)
        throws NetworkException, BadResponseException {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            Request request = new Request.Builder()
                .url("https://notify.bugsnag.com")
                .post(RequestBody.create(mediaType, getReportJson(report)))
                .build();
            Response response = okHttpClient.newCall(request).execute();

            if (response.code() != 200) {
                throw new BadResponseException("", response.code());
            }
        } catch (IOException e) {
            throw new NetworkException("Network Call failed", e);
        }
    }
}

setFilters

Sets which values should be removed from any MetaData objects before sending them to Bugsnag. Use this if you want to ensure you don’t send sensitive data such as passwords, and credit card numbers to our servers. Any keys which contain these strings will be filtered.

Bugsnag.setFilters(new String[]{"password", "credit_card_number"});

By default, filters is set to new String[] {"password"};

setIgnoreClasses

Sets for which exception classes we should not send exceptions to Bugsnag.

Bugsnag.setIgnoreClasses("java.net.UnknownHostException", "com.example.Custom");

setLaunchCrashThresholdMs

Sets the threshold in milliseconds for an uncaught error to be considered as a crash on launch. If a crash is detected on launch, Bugsnag will attempt to send the report synchronously. By default, this value is set at 5,000ms. Setting the value to 0 will disable this behaviour.

Configuration config = new Configuration("your-api-key");
config.setLaunchCrashThresholdMs(10000);
Bugsnag.init(context, config);

setMaxBreadcrumbs

Sets the maximum number of breadcrumbs which will be stored. Once the threshold is reached, the oldest breadcrumbs will be deleted.

Bugsnag.setMaxBreadcrumbs(50);

setNotifyReleaseStages

By default, Bugsnag will be notified of exceptions that happen in any releaseStage. If you would like to change which release stages notify Bugsnag of exceptions you can call setNotifyReleaseStages:

Bugsnag.setNotifyReleaseStages("production", "development", "testing");

setPersistUserBetweenSessions

Set whether or not Bugsnag should persist user information between application sessions. if set then any user information set will be re-used until Bugsnag.clearUser() is called

Configuration config = new Configuration("your-api-key-here");
config.setPersistUserBetweenSessions(true);
Bugsnag.init(this, config);

setProjectPackages

Sets which package names Bugsnag should consider as a part of the running application. We mark stacktrace lines as in-project if they originate from any of these packages.

Bugsnag.setProjectPackages("com.company.package1", "com.company.package2");

By default, projectPackages is set to be the package you called Bugsnag.init from.

setReleaseStage

If you would like to distinguish between errors that happen in different stages of the application release process (development, production, etc) you can set the releaseStage that is reported to Bugsnag.

Bugsnag.setReleaseStage("testing");

If you are running a debug build, we’ll automatically set this to “development”, otherwise it is set to “production”.

setSendThreads

Sets if we should collect and send thread state along with errors.

By default sendThreads is set to true.

Bugsnag.setSendThreads(false);

setSessionEndpoint

Set the endpoint to which tracked sessions reports are sent. This defaults to https://sessions.bugsnag.com, but should be overridden if you are using Bugsnag On-premise, to point to your own Bugsnag endpoint:

config.setSessionEndpoint("https://sessions.example.com");

setSessionTrackingApiClient

Sets the SessionTrackingApiClient implementation used to make network calls to the Sessions API. This may be useful if you have requirements such as certificate pinning and rotation, which are not supported by the default implementation.

Bugsnag.setSessionTrackingApiClient(new CertPinnedApiClient());

Implementations of SessionTrackingApiClient must throw a BadResponseException if the response code is not 202, and a NetworkException if the request could not be completed. The request body must match the structure specified in the Session Tracking API documentation.

setUser

Bugsnag helps you understand how many of your users are affected by each error. In order to do this, we need to send along user information with every exception.

If you would like to enable this, set the user. You can set the user id, which is usually the unique id to represent that user across all your apps, the user’s email address and the user’s name:

Bugsnag.setUser("userId", "user@email.com", "User Name");

setPersistUserBetweenSessions

Set whether or not Bugsnag should persist user information between application sessions. if set then any user information set will be re-used until Bugsnag.clearUser() is called

Configuration config = new Configuration("your-api-key-here");
config.setPersistUserBetweenSessions(true);
Bugsnag.init(this, config);

Customizing by build setting

Manifest placeholders

Bugsnag can be set up to use different configuration values for different build variants, by using the following manifest placeholders in your app’s build.gradle script.

android {
    defaultConfig {
        manifestPlaceholders = [
            // omit any of the following placeholders to use the default values
            bugsnagApiKey: "<api-key>",
            bugsnagBuildUUID: "<build-uuid>",
            bugsnagAppVersion: "1.0.0",
            bugsnagEndpoint: "https://notify.bugsnag.com",
            bugsnagReleaseStage: "<release-stage>",
            bugsnagSendThreads: true,
            bugsnagEnableExceptionHandler: true,
            bugsnagPersistUserBetweenSessions: false,
            bugsnagAutoCaptureSessions: true
        ]
    }
    productFlavors {
        free {
            manifestPlaceholders = [
                // override defaultConfig values here
            ]
        }
    }
}

For all the values you wish to configure, provide a meta-data element at the bottom of your manifest file.

<application>
    <meta-data android:name="com.bugsnag.android.API_KEY" android:value="${bugsnagApiKey}"/>
    <meta-data android:name="com.bugsnag.android.BUILD_UUID" android:value="${bugsnagBuildUUID}"/>
    <meta-data android:name="com.bugsnag.android.APP_VERSION" android:value="${bugsnagAppVersion}"/>
    <meta-data android:name="com.bugsnag.android.ENDPOINT" android:value="${bugsnagEndpoint}"/>
    <meta-data android:name="com.bugsnag.android.RELEASE_STAGE" android:value="${bugsnagReleaseStage}"/>
    <meta-data android:name="com.bugsnag.android.SEND_THREADS" android:value="${bugsnagSendThreads}"/>
    <meta-data android:name="com.bugsnag.android.ENABLE_EXCEPTION_HANDLER" android:value="${bugsnagEnableExceptionHandler}"/>
    <meta-data android:name="com.bugsnag.android.PERSIST_USER_BETWEEN_SESSIONS" android:value="${bugsnagPersistUserBetweenSessions}"/>
    <meta-data android:name="com.bugsnag.android.AUTO_CAPTURE_SESSIONS" android:value="${bugsnagAutoCaptureSessions}"/>
</application>

Finally, initialize Bugsnag in your Application class.

Bugsnag.init(this);

Using Resource values

Gradle resource values allow you to share custom fields and values between build files and app code. For example, to set API key in your build configuration, set a resource value in your Gradle file:

def bugsnag_api_key = project.hasProperty("api-key")
 ? project.property("api-key") : "your-api-key-here"

buildTypes {
    release {
        resValue("string", "bugsnag_api_key", "${bugsnag_api_key}")
    }
}

To load the value automatically when Bugsnag initializes, set a placeholder in your AndroidManifest.xml for the value:

<application ...>
    <meta-data android:name="com.bugsnag.android.API_KEY"
     android:value="@string/bugsnag_api_key"/>
</application>

Properties can also be loaded at runtime if needed (though not required if placeholders are set in AndroidManifest.xml):

Configuration config = new Configuration(getString(R.string.bugsnag_api_key));
Bugsnag.init(this, config);