Error Reporting Client Libraries

This page shows how to get started with the new 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

C#

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

Go

go get -u cloud.google.com/go/errorreporting

Java

If you are using Maven, add this to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-errorreporting</artifactId>
  <version>0.49.0-beta</version>
</dependency>
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud:google-cloud-errorreporting:0.49.0-beta'
If you are using SBT, add this to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-errorreporting" % "0.49.0-beta"

Node.js

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

PHP

composer require google/cloud-error-reporting

Python

For more on setting up your Python development environment, refer to Python Development Environment Setup Guide.
pip install --upgrade google-cloud-error_reporting

Ruby

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.

GCP Console

  1. Go to the Create service account key page in the GCP Console.

    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. Enter a name into the Service account name field.
  4. From the Role drop-down list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, 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 within Cloud Shell.

  1. Create the service account. Replace [NAME] with your desired service account name.

    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].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, 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].iam.gserviceaccount.com

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.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

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

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

Read more in the C# API Reference Documentation for the Stackdriver Error Reporting API Client Library.

public class ErrorReportingSample
{
    public static void Main(string[] args)
    {
        try
        {
            throw new Exception("Generic exception for testing Stackdriver Error Reporting");
        }
        catch (Exception e)
        {
            report(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: https://developers.google.com/identity/protocols/application-default-credentials.
    /// </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:
        // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report
        string formattedProjectId = string.Format("projects/{0}", projectId);

        // Add a service context to the report.  For more details see:
        // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events#ServiceContext
        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);
        request.Execute();
    }
}

Go

Read more in the Go API Reference Documentation for the Stackdriver Error Reporting API Client Library.

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

import (
	"log"
	"net/http"

	"cloud.google.com/go/errorreporting"
	"golang.org/x/net/context"
)

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 {
		log.Fatal(err)
	}
	defer errorClient.Close()
	defer errorClient.Flush()

	resp, err := http.Get("not-a-valid-url")
	if err != nil {
		logAndPrintError(err)
	} else {
		log.Print(resp.Status)
	}
}

func logAndPrintError(err error) {
	errorClient.Report(errorreporting.Entry{
		Error: err,
	})
	log.Print(err)
}

Java

Read more in the Java API Reference Documentation for the Stackdriver Error Reporting API Client Library.

import com.google.cloud.ServiceOptions;
import com.google.cloud.errorreporting.v1beta1.ReportErrorsServiceClient;
import com.google.devtools.clouderrorreporting.v1beta1.ErrorContext;
import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent;
import com.google.devtools.clouderrorreporting.v1beta1.SourceLocation;

/**
 * Snippet demonstrates using the Stackdriver Error Reporting API to report a custom error event.

 * 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()
          .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();
      // Report an event synchronously, use .reportErrorEventCallable for asynchronous reporting.
      reportErrorsServiceClient.reportErrorEvent(projectName, customErrorEvent);
    }
  }
}

Node.js

Read more in the Node.js API Reference Documentation for the Stackdriver Error Reporting API Client Library.

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

// On Node 6+ the following syntax can be used instead:
// const {ErrorReporting} = require('@google-cloud/error-reporting');

// With ES6 style imports via TypeScript or Babel, the following
// syntax can be used instead:
// import {ErrorReporting} from '@google-cloud/error-reporting';

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

// Reports a simple error
errors.report('Something broke!');

PHP

Read more in the PHP API Reference Documentation for the Stackdriver Error Reporting API Client Library.

<?php

// Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# [START error_reporting]
// Imports the Google Cloud client library
use Google\Cloud\Logging\LoggingClient;

// 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') ?: '1.0-dev';

// Instantiates a client
$logging = new LoggingClient([
    'projectId' => $projectId
]);

// The name of the log to write to
$logName = 'my-log';

// Selects the log to write to
$logger = $logging->logger($logName);

$handlerFunction = function (Exception $e) use ($logger, $service, $version) {
    // Creates the log entry with the exception trace
    $entry = $logger->entry([
        'message' => sprintf('PHP Warning: %s', $e),
        'serviceContext' => [
            'service' => $service,
            'version' => $version,
        ]
    ]);
    // Writes the log entry
    $logger->write($entry);

    print("Exception logged to Stack Driver Error Reporting" . PHP_EOL);
};

// Sets PHP's default exception handler
set_exception_handler($handlerFunction);

throw new Exception('This will be logged to Stack Driver Error Reporting');
# [END error_reporting]

Python

Read more in the Python API Reference Documentation for the Stackdriver Error Reporting API Client Library.

def simulate_error():
    from google.cloud import error_reporting

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

Ruby

Read more in the Ruby API Reference Documentation for the Stackdriver Error Reporting API Client Library.

require "google/cloud/error_reporting"

begin
  fail "Raise an exception for Error Reporting."
rescue => exception
  Google::Cloud::ErrorReporting.report exception
end

Additional Resources

Send feedback about...

Stackdriver Error Reporting