Bibliotecas de cliente do Error Reporting

Nesta página, apresentamos os primeiros passos para usar as bibliotecas de cliente do Cloud para a API Stackdriver Error Reporting. Leia mais sobre as bibliotecas de cliente das APIs do Cloud, incluindo as bibliotecas de cliente mais antigas das APIs do Google, em Explicações sobre bibliotecas de cliente.

Como instalar a biblioteca de cliente

C#

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em C#.
Install-Package Google.Cloud.ErrorReporting.V1Beta1 -pre

Go

go get cloud.google.com/go/errorreporting

Java

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Java.

Se você estiver usando o Maven, adicione o código abaixo ao arquivo pom.xml. Para mais informações sobre BOMs, consulte BOM das bibliotecas do Google Cloud Platform.

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

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

Se você estiver usando o Gradle, adicione isto às dependências:

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

Se você estiver usando o sbt, adicione o seguinte às suas dependências:

libraryDependencies += "com.google.cloud" % "google-cloud-errorreporting" % "0.162.0-beta"

Se você estiver usando o Visual Studio Code, o IntelliJ ou o Eclipse, poderá adicionar bibliotecas de cliente ao projeto usando estes plug-ins de IDE:

Os plug-ins também oferecem outras funcionalidades, como gerenciamento de chaves de contas de serviço. Consulte a documentação de cada plug-in para mais detalhes.

Node.js

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Node.js.
npm install --save @google-cloud/error-reporting

PHP

composer require google/cloud-error-reporting

Python

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Python.
pip install --upgrade google-cloud-error_reporting

Ruby

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Ruby.
gem install google-cloud-error_reporting

Como configurar a autenticação

Para executar a biblioteca de cliente, você precisa primeiro configurar a autenticação. Para isso, crie uma conta de serviço e defina uma variável de ambiente. Conclua os passos a seguir para configurar a autenticação. Para mais informações, consulte a documentação de autenticação do GCP.

Forneça credenciais de autenticação ao código do aplicativo definindo a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS. Essa variável se aplica somente à sessão de shell atual. Se você quiser que a variável seja aplicada em sessões de shell futuras, defina a variável no arquivo de inicialização de shell, por exemplo, no arquivo ~/.bashrc ou ~/.profile.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Exemplo:

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

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Exemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para prompt de comando:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Substitua KEY_PATH pelo caminho do arquivo JSON que contém suas credenciais.

Como usar a biblioteca de cliente

O exemplo a seguir mostra como usar a biblioteca de cliente.

C#

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

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

import (
	"context"
	"log"
	"net/http"

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

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()

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

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

Java

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.
 * <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()
          .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

// 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

// 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.
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('quickstart.php test exception');

Python

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

require "google/cloud/error_reporting"

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

Outros recursos