Error Reporting client libraries

This page shows how to get started with the Cloud Client Libraries for the Error Reporting API. Read more about the client libraries for Cloud APIs, including the older Google API Client Libraries, in Client Libraries Explained.

Installing the client library


For more information, see Setting Up a C# Development Environment.

Install-Package Google.Cloud.ErrorReporting.V1Beta1 -pre


For more information, see Setting Up a Go Development Environment.

go get


For more information, see Setting Up a Java Development Environment.

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.


  <!-- START_EXCLUDE -->
  <!-- END_EXCLUDE -->

If you are using Gradle, add the following to your dependencies:

implementation platform('')

implementation ''

If you are using sbt, add the following to your dependencies:

libraryDependencies += "" % "google-cloud-errorreporting" % "0.122.11-beta"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.


For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/error-reporting


For more information, see Using PHP on Google Cloud.

composer require google/cloud-error-reporting


For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-error-reporting


For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-error_reporting

Setting up authentication

To run the client library, you must first set up authentication. One way to do that is to create a service account and set an environment variable, as shown in the following steps. For other ways to authenticate, see Authenticating as a service account.

Cloud Console

Create a service account:

  1. In the Cloud Console, go to the Create service account page.

    Go to Create service account
  2. Select a project.
  3. In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name.

    In the Service account description field, enter a description. For example, Service account for quickstart.

  4. Click Create and continue.
  5. Click the Select a role field.

    Under Quick access, click Basic, then click Owner.

  6. Click Continue.
  7. Click Done to finish creating the service account.

    Do not close your browser window. You will use it in the next step.

Create a service account key:

  1. In the Cloud Console, click the email address for the service account that you created.
  2. Click Keys.
  3. Click Add key, then click Create new key.
  4. Click Create. A JSON key file is downloaded to your computer.
  5. Click Close.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace NAME with a name for the service account.

    gcloud iam service-accounts create NAME
  2. Grant permissions to the service account. Replace PROJECT_ID with your project ID.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="" --role="roles/owner"
  3. Generate the key file. Replace FILE_NAME with a name for the key file.

    gcloud iam service-accounts keys create FILE_NAME.json

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. This variable applies only to your current shell session. If you want the variable to apply to future shell sessions, set the variable in your shell startup file, for example in the ~/.bashrc or ~/.profile file.

Linux or macOS


Replace KEY_PATH with the path of the JSON file that contains your service account key.

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"


For PowerShell:


Replace KEY_PATH with the path of the JSON file that contains your service account key.

For example:


For command prompt:


Replace KEY_PATH with the path of the JSON file that contains your service account key.

Using the client library

The following example shows how to use the client library.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.ErrorReporting.V1Beta1;
using System;

public class ErrorReportingSample
    public static void Main(string[] args)
            throw new Exception("Generic exception for testing Stackdriver Error Reporting");
        catch (Exception e)
            Console.WriteLine("Stackdriver Error Report Sent");

    /// <summary>
    /// Report an exception to the Error Reporting service.
    /// </summary>
    private static void report(Exception e)
        // Create the report and execute the request.
        var reporter = ReportErrorsServiceClient.Create();

        // Get the project ID from the environement variables.
        var projectName = new ProjectName(

        // Add a service context to the report. For more details see:
        ServiceContext serviceContext = new ServiceContext()
            Service = "myapp",
            Version = "1.1",
        ReportedErrorEvent errorEvent = new ReportedErrorEvent()
            Message = e.ToString(),
            ServiceContext = serviceContext,
        reporter.ReportErrorEvent(projectName, errorEvent);


// Sample errorreporting_quickstart contains is a quickstart
// example for the Google Cloud Error Reporting API.
package main

import (


var errorClient *errorreporting.Client

func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	var err error
	errorClient, err = errorreporting.NewClient(ctx, projectID, errorreporting.Config{
		ServiceName: "myservice",
		OnError: func(err error) {
			log.Printf("Could not log error: %v", err)
	if err != nil {
	defer errorClient.Close()

	resp, err := http.Get("not-a-valid-url")
	if err != nil {

func logAndPrintError(err error) {
		Error: err,



 * Snippet demonstrates using the Cloud Error Reporting API to report a custom error event.
 * <p>This library is not required on App Engine, errors written to stderr are automatically written
 * to Cloud Error Reporting. It is also not required if you are writing logs to Cloud Logging.
 * Errors written to Cloud Logging that contain an exception or stack trace are automatically
 * written out to Cloud Error Reporting.
public class QuickStart {
  public static void main(String[] args) throws Exception {

    // Google Cloud Platform Project ID
    String projectId = (args.length > 0) ? args[0] : ServiceOptions.getDefaultProjectId();
    ProjectName projectName = ProjectName.of(projectId);

    // Instantiate an Error Reporting Client
    try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {

      // Custom error events require an error reporting location as well.
      ErrorContext errorContext =

      // Report a custom error event
      ReportedErrorEvent customErrorEvent =
              .setMessage("custom error event")
      // Report an event synchronously, use .reportErrorEventCallable for asynchronous reporting.
      reportErrorsServiceClient.reportErrorEvent(projectName, customErrorEvent);


// Imports the Google Cloud client library
const {ErrorReporting} = require('@google-cloud/error-reporting');

// Instantiates a client
const errors = new ErrorReporting();

// Reports a simple error'Something broke!');


// Imports the Cloud Client Library
use Google\Cloud\ErrorReporting\Bootstrap;
use Google\Cloud\Logging\LoggingClient;
use Google\Cloud\Core\Report\SimpleMetadataProvider;

// These variables are set by the App Engine environment. To test locally,
// ensure these are set or manually change their values.
$projectId = getenv('GCLOUD_PROJECT') ?: 'YOUR_PROJECT_ID';
$service = getenv('GAE_SERVICE') ?: 'error_reporting_quickstart';
$version = getenv('GAE_VERSION') ?: 'test';

// Instantiates a client
$logging = new LoggingClient([
    'projectId' => $projectId,
// Set the projectId, service, and version via the SimpleMetadataProvider
$metadata = new SimpleMetadataProvider([], $projectId, $service, $version);
// Create a PSR-3 compliant logger
$psrLogger = $logging->psrLogger('error-log', [
    'metadataProvider' => $metadata,
// Using the Error Reporting Bootstrap class, register your PSR logger as a PHP
// exception hander. This will ensure all exceptions are logged to Stackdriver.

print('Throwing a test exception. You can view the message at' . PHP_EOL);
throw new Exception('quickstart.php test exception');


def simulate_error():
    from import error_reporting

    client = error_reporting.Client()
        # simulate calling a method that's not defined
        raise NameError
    except Exception:


require "google/cloud/error_reporting"

  raise "Raise an exception for Error Reporting."
rescue StandardError => e e

Additional resources