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 web app integration

Installation

Using Gradle

Add bugsnag-spring to the dependencies section in your build.gradle:

implementation 'com.bugsnag:bugsnag-spring:3.+'

The latest available version of bugsnag-spring is v3.7.1.

Using Maven

Add bugsnag-spring as a dependency in your pom.xml

<dependency>
  <groupId>com.bugsnag</groupId>
  <version>[3.0,4.0)</version>
  <artifactId>bugsnag-spring</artifactId>
</dependency>

Then run mvn install to install the library.

Manual JAR installation

Download the latest release and place it with it’s dependencies in your app’s classpath.

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 Project Settings from your BugSnag 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

BugSnag attaches a Thread.UncaughtExceptionHandler, so after completing installation and basic configuration, unhandled exceptions will be automatically reported to your BugSnag dashboard.

If you do not want BugSnag to automatically report unhandled exceptions, set the sendUncaughtExceptions parameter to false when instantiating Bugsnag:

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 (Throwable exception) {
    bugsnag.notify(exception);
}

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 exception reports. This can be accomplished as follows:

bugsnag.addCallback((report) -> {
    // Will appear as the 'name' in the 'subsystem' tab
    report.addToTab("subsystem", "name", "Your subsystem name");
});

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 on your BugSnag dashboard.

bugsnag.addCallback((report) -> {
    report.setUser("User ID", "user@example.com", "User Name");
});

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 behaviour can be disabled using the setAutoCaptureSessions 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.

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