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.

Install the client library

C#

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

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

Go

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

go get cloud.google.com/go/errorreporting

Java

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.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.27.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-errorreporting</artifactId>
  </dependency>

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

implementation 'com.google.cloud:google-cloud-errorreporting:0.151.0-beta'

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

libraryDependencies += "com.google.cloud" % "google-cloud-errorreporting" % "0.151.0-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.

Node.js

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

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

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-error-reporting

Python

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

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

Ruby

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

gem install google-cloud-error_reporting

Set up authentication

When you use client libraries, you use Application Default Credentials (ADC) to authenticate. For information about setting up ADC, see Provide credentials for Application Default Credentials. For information about using ADC with client libraries, see Authenticate using client libraries.

Use the client library

The following example shows how to use the client library.

C#

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

public class ErrorReportingSample
{
    static String projectId;

    public static void Main(string[] args)
    {
	    // Set your Google Cloud Platform project ID via environment or explicitly
        if (args != null && args.Length > 0 && !String.IsNullOrEmpty(args[0]))
        {
            projectId = args[0];
        }
        else
        {
            projectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
        }

        try
        {
            throw new Exception("Something went wrong");
        }
        catch (Exception e)
        {
            ReportError(e);
            Console.WriteLine("Stackdriver Error Report Sent");
        }
    }


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

        // Optionally add a service context to the report. For more details see:
        // https://cloud.google.com/error-reporting/reference/rest/v1beta1/ServiceContext
        var assemblyName = System.Reflection.Assembly.GetEntryAssembly().GetName();
        var serviceContext = new ServiceContext()
        {
            Service = assemblyName.Name,
            Version = assemblyName.Version.ToString(),
        };
        var errorEvent = new ReportedErrorEvent()
        {
            Message = e.ToString(),
            ServiceContext = serviceContext,
        };
        reporter.ReportErrorEvent(projectName, errorEvent);
    }
}

Go

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

import (
	"context"
	"errors"
	"log"
	"os"

	"cloud.google.com/go/errorreporting"
)

var errorClient *errorreporting.Client

func main() {
	// Set your Google Cloud Platform project ID via environment or explicitly
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	args := os.Args[1:]
	if len(args) > 0 && args[0] != "" {
		projectID = args[0]
	}

	ctx := context.Background()
	var err error
	errorClient, err = errorreporting.NewClient(ctx, projectID, errorreporting.Config{
		ServiceName:    "errorreporting_quickstart",
		ServiceVersion: "0.0.0",
		OnError: func(err error) {
			log.Printf("Could not report the error: %v", err)
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer errorClient.Close()

	err = errors.New("something went wrong")
	if err != nil {
		logAndPrintError(err)
		return
	}
}

func logAndPrintError(err error) {
	/// Client autopopulates the error context of the error. For more details about the context see:
	/// https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorContext
	errorClient.Report(errorreporting.Entry{
		Error: err,
	})
	log.Print(err)
}

Java

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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);
    }
  }
}

Node.js

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

function quickstart() {
  try {
    throw new Error('Something went wrong');
  } catch (exception) {
    reportError(exception);
  }
}

function reportError(exception) {
  // Instantiates a client
  const errors = new ErrorReporting();

  // Reports an exception
  errors.report(exception.stack);
}

PHP

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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('GOOGLE_CLOUD_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.
Bootstrap::init($psrLogger);

print('Throwing a test exception. You can view the message at https://console.cloud.google.com/errors.' . PHP_EOL);
throw new Exception('Something went wrong');

Python

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def report_exception():
    from google.cloud import error_reporting

    client = error_reporting.Client()
    try:
        raise Exception("Something went wrong")
    except Exception:
        client.report_exception()

Ruby

To authenticate to Error Reporting, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/error_reporting"

begin
  raise "Something went wrong"
rescue StandardError => e
  Google::Cloud::ErrorReporting.report e
end

Additional resources