Instrument Java apps for Error Reporting

You can send error reports to Error Reporting from Java applications by using the Error Reporting package for Java. Use the Error Reporting package for Java to create error groups for the following cases:

  • Your log bucket has customer-managed encryption keys (CMEK).
  • Your log buckets aren't in the global region.
  • You want to report custom error events.

Error Reporting is integrated with some Google Cloud services, such as App Engine, Compute Engine, and Google Kubernetes Engine. Error Reporting displays the errors that are logged to Cloud Logging by applications running on those services. For more information, go to Running on Google Cloud on this page.

You can also send error data to Error Reporting using Logging. For information on the data formatting requirements, read Formatting error messages in Logging.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Error Reporting API .

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Error Reporting API .

    Enable the API

Install the client library

The Error Reporting package for Java lets you monitor and view errors reported by Java applications running nearly anywhere.

For more information on installation, read the documentation for the Error Reporting package for Java. You can also report issues using the issue tracker.

Configure the client library

You can customize the behavior of the Error Reporting package for Java. See the Java API reference documentation.

Run apps on Google Cloud

To create error groups by using projects.events.report, your service account requires the Error Reporting Writer role (roles/errorreporting.writer).

Some Google Cloud services automatically grant the Error Reporting Writer role (roles/errorreporting.writer) to the appropriate service account. However, you must grant this role to the appropriate service account for some services.

App Engine flexible environment

App Engine grants the Error Reporting Writer role (roles/errorreporting.writer) to your default service account automatically.

The Error Reporting package for Java can be used without needing to explicitly provide credentials.

Error Reporting is automatically enabled for App Engine flexible environment applications. No additional setup is required.

@WebServlet(name = "Error reporting", value = "/error")
public class ErrorReportingExample extends HttpServlet {

  private Logger logger = Logger.getLogger(ErrorReportingExample.class.getName());

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    // errors logged to stderr / Cloud logging with exceptions are automatically reported.
    logger.log(Level.SEVERE, "exception using log framework", new IllegalArgumentException());

    // use the error-reporting client library only if you require logging custom error events.
    logCustomErrorEvent();

    // runtime exceptions are also automatically reported.
    throw new RuntimeException("this is a runtime exception");
  }

  private void logCustomErrorEvent() {
    try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
      // Custom error events require an error reporting location as well.
      ErrorContext errorContext =
          ErrorContext.newBuilder()
              .setReportLocation(
                  SourceLocation.newBuilder()
                      .setFilePath("Test.java")
                      .setLineNumber(10)
                      .setFunctionName("myMethod")
                      .build())
              .build();
      // Report a custom error event
      ReportedErrorEvent customErrorEvent =
          ReportedErrorEvent.getDefaultInstance()
              .toBuilder()
              .setMessage("custom error event")
              .setContext(errorContext)
              .build();

      // default project id
      ProjectName projectName = ProjectName.of(ServiceOptions.getDefaultProjectId());
      reportErrorsServiceClient.reportErrorEvent(projectName, customErrorEvent);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Exception encountered logging custom event", e);
    }
  }
}

Google Kubernetes Engine

To use Error Reporting with Google Kubernetes Engine, do the following:

  1. Ensure that the service account to be used by your container has been granted the Error Reporting Writer role (roles/errorreporting.writer).

    You can use either the Compute Engine default service account or a custom service account.

    For information about granting roles, see Manage access to projects, folders, and organizations.

  2. Create your cluster and grant the cluster the cloud-platform access scope.

    For example, the following create command specifies the cloud-platform access scope and a service account:

    gcloud container clusters create CLUSTER_NAME --service-account  SERVICE_ACCT_NAME --scopes=cloud-platform
    

Compute Engine

To use Error Reporting with Compute Engine VM instances, do the following:

  1. Ensure that the service account to be used by your VM instance has been granted the Error Reporting Writer role (roles/errorreporting.writer).

    You can use either the Compute Engine default service account or a custom service account.

    For information about granting roles, see Manage access to projects, folders, and organizations.

  2. In the navigation panel of the Google Cloud console, select Compute Engine, and then select VM instances:

    Go to VM instances

  3. Select the VM instance that you want to receive the cloud-platform access scope.

  4. Click Stop, and then click Edit.

  5. In the Identity and API access section, select a service account that has the Error Reporting Writer role (roles/errorreporting.writer).

  6. In the Access scopes section, select Allow full access to all Cloud APIs, and then save your changes.

  7. Click Start/Resume.

Example

Exceptions logged using the Cloud Logging Logback Appender or java.util.logging Handler are automatically reported to the Error Reporting console.

The following sample demonstrates using the Java client library to report a custom error event:

import com.google.cloud.ServiceOptions;
import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorsServiceClient;
import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Snippet demonstrates using the Error Reporting API to report an exception.
 * <p>
 * When the workload runs on App Engine, GKE, Cloud Functions or another managed environment,
 * printing the exception's stack trace to stderr will automatically report the error
 * to Error Reporting.
 */
public class QuickStart {

  static String projectId;

  public static void main(String[] args) throws Exception {
    // Set your Google Cloud Platform project ID via environment or explicitly
    projectId = ServiceOptions.getDefaultProjectId();
    if (args.length > 0) {
      projectId = args[0];
    } else {
      String value = System.getenv("GOOGLE_CLOUD_PROJECT");
      if (value != null && value.isEmpty()) {
        projectId = value;
      }
    }

    try {
      throw new Exception("Something went wrong");
    } catch (Exception ex) {
      reportError(ex);
    }
  }

  /**
   * Sends formatted error report to Google Cloud including the error context.
   *
   * @param ex Exception containing the error and the context.
   * @throws IOException if fails to communicate with Google Cloud
   */
  private static void reportError(Exception ex) throws IOException {
    try (ReportErrorsServiceClient serviceClient = ReportErrorsServiceClient.create()) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);

      ReportedErrorEvent errorEvent = ReportedErrorEvent.getDefaultInstance()
          .toBuilder()
          .setMessage(sw.toString())
          .build();
      // If you need to report an error asynchronously, use reportErrorEventCallable()
      // method
      serviceClient.reportErrorEvent(ProjectName.of(projectId), errorEvent);
    }
  }
}

See the Java API Reference Documentation on how to retrieve and manage error statistics as well as data for individual events.

Run apps in a local development environment

To use the Error Reporting package for Java in a local development environment, such as running the library on your own workstation, you must provide your Error Reporting package for Java with the local application default credentials. For more information, see Authenticate to Error Reporting.

To use the Java samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. Create local authentication credentials for your Google Account:

    gcloud auth application-default login

For more information, see Set up authentication for a local development environment.

The projects.events.report method also supports API keys. If you want to use API keys for authentication, you do not need to set up a local Application Default Credentials file. For more information, see Create an API key in the Google Cloud authentication documentation.

Viewing error reports

In the navigation panel of the Google Cloud console, select Error Reporting, and then select your Google Cloud project:

Go to Error Reporting

For more information, see Viewing Errors.