Spring integration guide

Add BugSnag to your Java Spring and Spring Boot projects to automatically capture and report exceptions on production.

New to BugSnag? Create an account

Looking for performance monitoring? See our performance guide

Installation

Using Gradle

Add bugsnag to the dependencies section in your build.gradle or build.gradle.kts:

implementation 'com.bugsnag:bugsnag:4.+'
implementation("com.bugsnag:bugsnag:4.+")

The latest available version of bugsnag-java is v4.0.0.

Using Maven

Add bugsnag as a dependency in your pom.xml:

<dependency>
  <groupId>com.bugsnag</groupId>
  <version>[4.0,5.0)</version>
  <artifactId>bugsnag</artifactId>
</dependency>

SLF4J

BugSnag Java uses SLF4J for internal logging, which provides a facade to several popular logging libraries. If you do not specify which logging library you wish to use, a no-operation implementation which outputs a build warning will be used.

To suppress this build warning, you should add one of the SLF4J bindings as either a Gradle/Maven dependency in your project, or as a Jar file.

SLF4J

BugSnag Spring uses SLF4J for internal logging, which provides a facade to several popular logging libraries. If you do not specify which logging library you wish to use, a no-operation implementation which outputs a build warning will be used.

To suppress this build warning, you should add one of the SLF4J bindings as either a Gradle/Maven dependency in your project, or as a Jar file.

Compatibility

The minimum supported version of Spring Boot is 1.4.0.

If using Spring without Spring Boot the minimum supported version is 4.2.0.

Basic configuration

Using Spring annotations

The simplest way to configure BugSnag for Spring is to use Spring Annotations.

  1. Create a Spring Configuration class which exposes Bugsnag as a Spring bean and imports the configuration class BugsnagSpringConfiguration to begin capturing exceptions:

    @Configuration
    @Import(BugsnagSpringConfiguration.class)
    public class BugsnagConfig {
        @Bean
        public Bugsnag bugsnag() {
            return new Bugsnag("your-api-key-here");
        }
    }
    

    You can find your API key in your project’s settings (shortcut: gs) in the dashboard.

  2. Inject the Bugsnag bean into your Spring managed bean to report handled exceptions:

    @Autowired
    private Bugsnag bugsnag;
    

Using XML configuration

  1. If you’re using XML configuration instead of Spring Annotations, you can configure a Bugsnag bean and a BugsnagSpringConfiguration bean to begin capturing exceptions:

    <context:annotation-config />
    <bean id="bugsnag"
          class="com.bugsnag.Bugsnag">
      <constructor-arg name="apiKey"
                       value="your-api-key-here"/>
    </bean>
    <bean id="bugsnagSpringConfiguration"
          class="com.bugsnag.BugsnagSpringConfiguration"/>
    
  2. Add a setter for the Bugsnag bean into your managed bean:

    private Bugsnag bugsnag;
    
    public void setBugsnag(Bugsnag bugsnag) {
      this.bugsnag = bugsnag;
    }
    
  3. Inject Bugsnag into your bean:

    <bean id="example" class="com.example.ExampleBean">
      <property name="bugsnag" ref="bugsnag"/>
    </bean>
    

Logback configuration

If you use logback you can configure a BugSnag log appender to automatically report logged throwables. See configuring logback for additional setup instructions.

Further configuration

If you’d like to configure BugSnag further, check out the configuration options reference.

Reporting unhandled exceptions

After completing installation and basic configuration, unhandled exceptions will be automatically reported to your BugSnag dashboard.

BugSnag attaches a Thread.UncaughtExceptionHandler to detect and report any uncaught exceptions thrown in your application.

If you do not want BugSnag to automatically report unhandled exceptions, you can disable this using the autoDetectErrors configuration option:

Bugsnag bugsnag = new Bugsnag("your-api-key-here", false);

In addition to exceptions reported from Thread.UncaughtExceptionHandler, unhandled exceptions are automatically reported to BugSnag if you are using:

Spring MVC

Unhandled exceptions thrown when the DispatcherServlet processes MVC and REST API requests are automatically reported to BugSnag.

Exceptions thrown from @Controller and @RestController methods will have a default severity of ERROR.

Exceptions that are automatically assigned an HTTP response status by Spring (see DefaultHandlerExceptionResolver) will have a default severity of INFO for 4XX responses (bad request) and ERROR for 500 responses.

Scheduled tasks

Uncaught exceptions thrown in @Scheduled annotated methods will be automatically reported to BugSnag.

Async methods

In order to automatically report uncaught exceptions thrown in @Async methods the following configuration needs to be added to your application:

@Configuration
public class BugsnagAsyncConfig extends AsyncConfigurerSupport {
    @Autowired
    private Bugsnag bugsnag;

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new BugsnagAsyncExceptionHandler(bugsnag);
    }
}

If your method returns a Future, you will need to wrap the call to future.get with a try-catch and notify bugsnag of the error:

Future<Data> future = restService.retrieveData();

try {
    Data data = future.get();
} catch (Exception exc) {
    bugsnag.notify(exc);
}

Reporting handled exceptions

If you would like to send handled exceptions to BugSnag, you can pass any Throwable object to the bugsnag.notify method:

try {
    // Some potentially crashy code
} catch (Exception exception) {
    bugsnag.notify(exception);
}

This will create and send an event for a “handled” error, with the default severity “warning”.

Adding diagnostics or adjusting severity

It can often be helpful to adjust the severity or attach custom diagnostics to handled exceptions. For more information, see Reporting handled exceptions.

Using the logback appender

If you configure the logback appender exceptions will be sent to BugSnag when you include the Throwable parameter in a Logger call:

private static final Logger logger = Logger.getLogger(MyClass.class);

try {
    // Some potentially crashy code
} catch (Throwable exception) {
    logger.warn("Something went wrong here", exception);
}

For configuration instructions see configuring logback.

Sending diagnostic data

It can often be helpful to attach application-specific diagnostic data to error reports. This can be accomplished by setting a callback which will be invoked before any reports are sent to BugSnag:

bugsnag.addOnError((event) -> {
    event.addMetadata("subsystem", "name", "Your subsystem name");
    return true;
});

For more information, see Customizing error reports.

Identifying users

In order to correlate errors with customer reports, or to see a list of users who experienced each error, it is helpful to capture and display user information. BugSnag includes helpers for attaching an identifier, email address and name to reports that will be searchable in the dashboard.

By default we will generate a unique ID and send this ID along with every error report from an individual device. If you would like to override this identifier you can set the user ID property.

bugsnag.addOnError((event) -> {
    event.setUser("User ID", "user@example.com", "User Name");
    return true;
});

For more information, see Customizing error reports.

HTTP requests

BugSnag will automatically populate details of requests such as the client IP address and request URL for handled and unhandled exceptions.

Check out the full list of captured data for more details.

Session tracking

BugSnag tracks the number of “sessions” that happen within your application. This allows you to compare stability scores between releases and helps you to understand the quality of your releases.

For Spring applications, a session is captured and reported for each HTTP request which uses Spring MVC. This behavior can be disabled using the autoCaptureSessions configuration option.

If you want full control over what is deemed a session, you can switch off automatic session tracking with the setAutoCaptureSessions option, and call startSession() directly.

Declaring feature flags and experiments

Monitor errors as you roll out features or run experiments and A/B tests by declaring your feature flag and experiment usage in the BugSnag SDK. You can use the Features dashboard to identify whether these features have introduced errors into your app.

bugsnag.addFeatureFlag("Checkout button color", "Blue");
bugsnag.addFeatureFlag("New checkout flow");

For more information, see Feature flags.

Tracking releases

Configure your app version to see the release that each error was introduced in.

bugsnag.setAppVersion("1.0.0");

Then set up a build tool integration to enable linking to code in your source control provider from the releases dashboard, timeline annotations, and stack traces.

Next steps