为 Java 应用添加插桩以使用 Error Reporting

您可以使用 Java 版 Error Reporting 软件包,从 Java 应用向 Error Reporting 发送错误事件。 使用 Java 版 Error Reporting 程序包可针对以下情况创建错误组:

  • 包含日志条目的日志存储桶具有客户管理的加密密钥 (CMEK)
  • 日志存储桶满足以下条件之一:
    • 日志存储桶存储在日志条目源自的项目中。
    • 日志条目被路由到一个项目,然后该项目将这些日志条目存储在自己拥有的日志存储桶中。
  • 您想报告自定义错误事件。

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 版 Error Reporting 软件包,您可以监控和查看几乎在任何位置运行的 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 Writer 角色 (roles/errorreporting.writer)。

某些 Google Cloud 服务会自动向相应的服务账号授予 Error Reporting (when used with Stackdriver) 写入者角色 (roles/errorreporting.writer)。不过,对于某些服务,您必须将此角色授予相应的服务账号。

Cloud Run 和 Cloud Run functions

Cloud Run 使用的默认服务账号具有Error Reporting (与 Stackdriver 搭配使用时) 写入者角色 (roles/errorreporting.writer) 的权限。

无需明确提供凭据即可使用 Java 版 Error Reporting 软件包。

Cloud Run 已配置为自动使用 Error Reporting。未处理的 JavaScript 异常将在 Logging 中显示,并且会由 Error Reporting 进行处理,而无需使用 Java 版 Error Reporting 软件包。

App Engine 柔性环境

App Engine 会自动向您的默认服务账号授予 Error Reporting Writer 角色 (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

如需将 Error Reporting 与 Google Kubernetes Engine 搭配使用,请执行以下操作:

  1. 确保您的容器要使用的服务账号已被授予 Error Reporting Writer 角色 (roles/errorreporting.writer)。

    您可以使用 Compute Engine 默认服务账号或自定义服务账号。

    如需了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

  2. 创建集群,并向该集群授予 cloud-platform 访问权限范围

    例如,以下创建命令指定了 cloud-platform 访问权限范围和服务账号:

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

Compute Engine

如需将 Error Reporting 与 Compute Engine 虚拟机实例搭配使用,请执行以下操作:

  1. 确保虚拟机实例要使用的服务账号已被授予Error Reporting (when used with Stackdriver) Writer 角色 (roles/errorreporting.writer)。

    您可以使用 Compute Engine 默认服务账号或自定义服务账号。

    如需了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

  2. 在 Google Cloud 控制台中,前往虚拟机实例页面:

    前往虚拟机实例

    如果您使用搜索栏查找此页面,请选择子标题为 Compute Engine 的结果。

  3. 选择要接收 cloud-platform 访问权限范围的虚拟机实例。

  4. 点击停止,然后点击修改

  5. 身份和 API 访问权限部分,选择具有 Error Reporting Writer 角色 (roles/errorreporting.writer) 的服务账号。

  6. 访问权限范围部分中,选择授予对所有 Cloud API 的完整访问权限,然后保存更改。

  7. 点击启动/恢复

示例

使用 Cloud Logging Logback Appenderjava.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. 如果您使用的是本地 shell,请为您的用户账号创建本地身份验证凭证:

    gcloud auth application-default login

    如果您使用的是 Cloud Shell,则无需执行此操作。

    如果系统返回身份验证错误,并且您使用的是外部身份提供方 (IdP),请确认您已 使用联合身份登录 gcloud CLI

如需了解详情,请参阅 为本地开发环境设置身份验证

projects.events.report 方法也支持 API 密钥。 如果您要使用 API 密钥进行身份验证,则无需设置本地应用默认凭据文件。 如需了解详情,请参阅 Google Cloud 身份验证文档中的创建 API 密钥

查看错误组

在 Google Cloud 控制台中,前往 Error Reporting 页面:

前往 Error Reporting

您也可以使用搜索栏查找此页面。

如需了解详情,请参阅查看和过滤错误组