Error Reporting 用戶端程式庫

本頁將說明如何開始使用 Stackdriver 錯誤報告 API 的 Cloud 用戶端程式庫。 如要進一步瞭解 Cloud API 的用戶端程式庫以及舊版 Google API 用戶端程式庫,請參閱用戶端程式庫說明

安裝用戶端程式庫

C#

相關詳細資訊請參閱設定 C# 開發環境
Install-Package Google.Cloud.ErrorReporting.V1Beta1 -pre

Go

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

Java

相關詳細資訊請參閱設定 Java 開發環境。 如果您是使用 Maven,請在 pom.xml 檔案中新增以下指令:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-errorreporting</artifactId>
  <version>0.93.0-beta</version>
</dependency>
如果您是使用 Gradle,請在相依元件中新增以下指令:
compile 'com.google.cloud:google-cloud-errorreporting:0.93.0-beta'
如果您是使用 SBT,請在相依元件中新增以下指令:
libraryDependencies += "com.google.cloud" % "google-cloud-errorreporting" % "0.93.0-beta"

如果您使用 IntelliJ 或 Eclipse,可以使用以下 IDE 外掛程式將用戶端程式庫加入專案中:

外掛程式還提供其他功能,例如服務帳戶適用的金鑰管理。詳情請參閱各外掛程式的說明文件。

Node.js

相關詳細資訊請參閱設定 Node.js 開發環境
npm install --save @google-cloud/error-reporting

PHP

composer require google/cloud-error-reporting

Python

相關詳細資訊請參閱設定 Python 開發環境
pip install --upgrade google-cloud-error_reporting

Ruby

相關詳細資訊請參閱設定 Ruby 開發環境
gem install google-cloud-error_reporting

設定驗證

如要執行用戶端程式庫,您必須先建立服務帳戶並設定環境變數以設定驗證。完成以下步驟即可設定驗證程序,詳情請參閱 GCP 驗證說明文件

GCP 主控台

  1. 在 GCP 主控台中,前往「Create service account key」(建立服務帳戶金鑰) 頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面
  2. 從 [Service account] (服務帳戶) 清單中選取 [New service account] (新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 從 [Role] (角色) 清單中,選取 [Project] (專案) > [Owner] (擁有者)

    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。以後您可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  5. 點選 [建立]。一個包含您金鑰的 JSON 檔案會下載到電腦中。

指令列

您可以使用本機電腦上的 Cloud SDK,或在 Cloud Shell 內執行下列指令。

  1. 建立服務帳戶。將 [NAME] 換成服務帳戶的名稱。

    gcloud iam service-accounts create [NAME]
  2. 向服務帳戶授予權限。用您的專案 ID 取代 [PROJECT_ID]

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。您稍後可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  3. 產生金鑰檔案。用金鑰檔案的名稱取代 [FILE_NAME]

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

設定環境變數 GOOGLE_APPLICATION_CREDENTIALS 來為應用程式程式碼提供驗證憑證。 將 [PATH] 改成包含您的服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 改成檔案名稱。 此變數僅適用於您目前的殼層工作階段,所以如果您開啟新的工作階段,請再次設定變數。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

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

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

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

使用命令提示字元:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

使用用戶端程式庫

以下範例顯示如何使用用戶端程式庫。

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.

 * 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

<?php

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

// 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');

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

其他資源

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Stackdriver 錯誤報告
需要協助嗎?請前往我們的支援網頁