為 Java 應用程式檢測錯誤報告

您可以使用 Java 適用的 Error Reporting 套件,從 Java 應用程式傳送錯誤事件至 Error Reporting。 使用 Java 適用的 Error Reporting 套件,為下列情況建立錯誤群組:

  • 含有記錄檔項目的記錄檔 bucket 具有客戶自行管理的加密金鑰 (CMEK)
  • 記錄檔 bucket 符合下列其中一項條件:
    • 記錄 bucket 儲存在記錄項目來源的專案中。
    • 記錄項目已轉送至專案,然後該專案將這些記錄項目儲存在其擁有的記錄 bucket 中。
  • 您想回報自訂錯誤事件。

Error Reporting 已與部分 Google Cloud 服務整合,如 Cloud Run 函式App EngineCompute EngineGoogle Kubernetes Engine。Error Reporting 會顯示在這些服務上執行的應用程式記錄到 Cloud Logging 的錯誤事件。詳情請參閱本頁面的「在 Google Cloud上執行」一節。

另外,您也可以使用 Logging,將錯誤事件傳送至 Error Reporting。如要瞭解資料格式要求,請參閱「格式化記錄項目以回報錯誤事件」。

事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

安裝用戶端程式庫

Java 適用的錯誤報告套件可讓您監控及查看在各處執行的 Java 應用程式回報的錯誤事件。

    如果您使用 Maven,請將下列指令新增到 pom.xml 檔案中。如要進一步瞭解 BOM,請參閱 Google Cloud Platform 程式庫 BOM

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

    如果您使用 Gradle,請將下列指令新增到依附元件中:

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

    如果您使用 sbt,請在依附元件中加入以下指令:

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

    如果您使用 Visual Studio Code 或 IntelliJ,可以利用下列 IDE 外掛程式,將用戶端程式庫新增到專案中:

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

如要進一步瞭解安裝,請參閱 Java 適用的 Error Reporting 套件說明文件。您也可以使用問題追蹤工具報告問題。

設定用戶端程式庫

您可以自訂 Java 適用的 Error Reporting 套件行為。請參閱 Java API 參考說明文件

在 Google Cloud上執行應用程式

如要使用 projects.events.report 建立錯誤群組,服務帳戶必須具備Error Reporting 撰寫者角色 (roles/errorreporting.writer)。

部分 Google Cloud 服務會自動將 Error Reporting 寫入者角色 (roles/errorreporting.writer) 授予適當的服務帳戶。不過,您必須為部分服務的適當服務帳戶授予這個角色。

Cloud Run 和 Cloud Run functions

Cloud Run 使用的預設服務帳戶具有 Error Reporting 寫入者角色 (roles/errorreporting.writer) 的權限。

不需要明確提供憑證,即可使用 Java 適用的 Error Reporting 套件。

Cloud Run 設定為自動使用 Error Reporting。未處理的 JavaScript 例外狀況會出現在 Logging 之中並由 Error Reporting 處理,不需使用 Java 適用的 Error Reporting 套件。

App Engine 彈性環境

App Engine 會自動將 Error Reporting 寫入者角色 (roles/errorreporting.writer) 授予預設服務帳戶。

不需要明確提供憑證,即可使用 Java 適用的 Error Reporting 套件。

系統會自動為 App Engine 彈性環境應用程式啟用 Error Reporting。您不需要另外進行設定。

@WebServlet(name = "Error reporting", value = "/error")
public class ErrorReportingExample extends HttpServlet {

  private Logger logger = Logger.getLogger(ErrorReportingExample.class.getName());

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    // errors logged to stderr / Cloud logging with exceptions are automatically reported.
    logger.log(Level.SEVERE, "exception using log framework", new IllegalArgumentException());

    // use the error-reporting client library only if you require logging custom error events.
    logCustomErrorEvent();

    // runtime exceptions are also automatically reported.
    throw new RuntimeException("this is a runtime exception");
  }

  private void logCustomErrorEvent() {
    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();

      // default project id
      ProjectName projectName = ProjectName.of(ServiceOptions.getDefaultProjectId());
      reportErrorsServiceClient.reportErrorEvent(projectName, customErrorEvent);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Exception encountered logging custom event", e);
    }
  }
}

Google Kubernetes Engine

如要在 Google Kubernetes Engine 中使用 Error Reporting,請按照下列步驟操作:

  1. 請確保容器使用的服務帳戶已取得 Error Reporting 寫入者角色 (roles/errorreporting.writer)。

    您可以使用 Compute Engine 預設服務帳戶或自訂服務帳戶。

    如要瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

  2. 建立叢集,並授予叢集 cloud-platform access scope

    舉例來說,下列建立指令會指定 cloud-platform 存取範圍和服務帳戶:

    gcloud container clusters create CLUSTER_NAME --service-account  SERVICE_ACCT_NAME --scopes=cloud-platform
    

Compute Engine

如要搭配使用 Error Reporting 與 Compute Engine VM 執行個體,請完成下列步驟:

  1. 確認 VM 執行個體使用的服務帳戶已取得 Error Reporting 寫入者角色 (roles/errorreporting.writer)。

    您可以使用 Compute Engine 預設服務帳戶或自訂服務帳戶。

    如要瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

  2. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往「VM instances」(VM 執行個體) 頁面

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Compute Engine」的結果

  3. 選取要接收cloud-platform 存取範圍的 VM 執行個體。

  4. 按一下「停止」,然後按一下「編輯」

  5. 在「Identity and API access」(身分及 API 存取權) 區段,選取具有 Error Reporting 寫入者角色 (roles/errorreporting.writer) 的服務帳戶。

  6. 在「存取權範圍」專區,選取「允許所有 Cloud API 的完整存取權」,然後儲存變更。

  7. 點選「啟動/重新啟用」

範例

使用 Cloud Logging Logback 附加程式java.util.logging Handler記錄的例外狀況會自動回報至 Error Reporting 主控台。

下列範例說明如何使用 Java 用戶端程式庫回報自訂錯誤事件:

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

請參閱 Java API 參考說明文件,進一步瞭解如何擷取及管理錯誤統計資料與個別事件的資料。

在本機開發環境中執行應用程式

如要在本機開發環境中使用 Java 適用的 Error Reporting 套件 (例如在自己的工作站上執行程式庫),您必須為 Java 適用的 Error Reporting 套件提供本機應用程式預設憑證。詳情請參閱「向 Error Reporting 進行驗證」。

如要在本機開發環境中使用本頁面的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

  1. 安裝 Google Cloud CLI。

  2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

    gcloud auth application-default login

    如果您使用 Cloud Shell,則不需要執行這項操作。

    如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI

詳情請參閱 這篇文章,瞭解如何設定本機開發環境的驗證機制。

projects.events.report 方法也支援 API 金鑰。如要使用 API 金鑰進行驗證,則不需要設定本機應用程式預設憑證檔案。詳情請參閱 Google Cloud 驗證說明文件中的「建立 API 金鑰」。

查看錯誤群組

前往 Google Cloud 控制台的「Error Reporting」頁面:

前往 Error Reporting

您也可以透過搜尋列找到這個頁面。

詳情請參閱「查看及篩選錯誤群組」。