Error Reporting Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Stackdriver Error Reporting API. Read more about the client libraries for Cloud APIs, including the older Google APIs 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


go get -u


For more information, see Setting Up a Java Development Environment. If you are using Maven, add the following to your pom.xml file:
If you are using Gradle, add the following to your dependencies:
compile ''
If you are using SBT, add the following to your dependencies:
libraryDependencies += "" % "google-cloud-errorreporting" % "0.92.0-beta"

If you're using 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


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 by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP Console

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

    Go to the Create Service Account Key page
  2. From the Service account list, select New service account.
  3. In the Service account name field, enter a name.
  4. From the Role list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using the GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

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 "serviceAccount:[NAME]@[PROJECT_ID]" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID]

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS


For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"


With PowerShell:


For example:


With command prompt:


Using the client library

The following example shows how to use the client library.


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>
    /// Create the Error Reporting service (<seealso cref="ClouderrorreportingService"/>)
    /// with the Application Default Credentials and the proper scopes.
    /// See:
    /// </summary>
    private static ClouderrorreportingService CreateErrorReportingClient()
        // Get the Application Default Credentials.
        GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

        // Add the needed scope to the credentials.
        credential = credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

        // Create the Error Reporting Service.
        ClouderrorreportingService service = new ClouderrorreportingService(new BaseClientService.Initializer
            HttpClientInitializer = credential,
        return service;

    /// <summary>
    /// Creates a <seealso cref="ReportRequest"/> from a given exception.
    /// </summary>
    private static ReportRequest CreateReportRequest(Exception e)
        // Create the service.
        ClouderrorreportingService service = CreateErrorReportingClient();

        // Get the project ID from the environement variables.
        string projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");

        // Format the project id to the format Error Reporting expects. See:
        string formattedProjectId = string.Format("projects/{0}", projectId);

        // Add a service context to the report.  For more details see:
        ServiceContext serviceContext = new ServiceContext()
            Service = "myapp",
            Version = "8c1917a9eca3475b5a3686d1d44b52908463b989",
        ReportedErrorEvent errorEvent = new ReportedErrorEvent()
            Message = e.ToString(),
            ServiceContext = serviceContext,
        return new ReportRequest(service, errorEvent, formattedProjectId);

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


// 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 Stackdriver 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 Stackdriver Error Reporting.
 * It is also not required if you are writing logs to Stackdriver Logging.
 * Errors written to Stackdriver Logging that contain an exception or stack trace
 * are automatically written out to Stackdriver 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 = ErrorContext.newBuilder()

      //Report a custom error event
      ReportedErrorEvent customErrorEvent = ReportedErrorEvent.getDefaultInstance()
          .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-4 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 => exception exception

Additional Resources

Was deze pagina nuttig? Laat ons weten hoe goed we u hebben geholpen:

Feedback verzenden over...

Stackdriver Error Reporting
Hulp nodig? Ga naar onze ondersteuningspagina.