对 Java 应用进行插桩处理以进行 Error Reporting

您可以通过 Java 将错误报告发送到 Error Reporting 如何使用 Google Cloud 中的 Java 版 Error Reporting 软件包。 使用 Java 版 Error Reporting 程序包可为以下情况创建错误组:

  • 您的日志存储桶包含客户管理的加密密钥 (CMEK)
  • 您的日志存储分区不在 global 区域。
  • 您想要报告自定义错误事件。

Error Reporting 已与某些 Google Cloud 服务集成,例如 App EngineCompute EngineGoogle Kubernetes Engine。Error Reporting 可显示在这些服务上运行的应用记录到 Cloud Logging 中的错误。如需了解详情,请参阅 在 Google Cloud 上运行 页面。

您还可以使用 Logging 将错误数据发送到 Error Reporting。如需了解数据格式设置要求,请参阅设置 Logging 中的错误消息格式

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Error Reporting API 。

    启用 API

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

    Go to project selector

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Error Reporting API 。

    启用 API

安装客户端库

借助 Java 版 Error Reporting 程序包,您可以监控和查看 几乎可在任何位置运行的 Java 应用。

如需详细了解如何安装,请参阅 Java 版 Error Reporting 软件包的文档。您还可以使用问题跟踪器来报告问题。

配置客户端库

您可以自定义 Java 版 Error Reporting 程序包的行为。请参阅 Java API 参考文档

在 Google Cloud 上运行应用

要使用以下方法创建错误组: projects.events.report,您的服务账号需要 Error Reporting 写入者角色 (roles/errorreporting.writer)。

某些 Google Cloud 服务会自动 Error Reporting Writer 角色 (roles/errorreporting.writer) 服务账号。但是,您必须将此角色授予相应的服务 使用部分服务

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 写入者角色 (roles/errorreporting.writer)。

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

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

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

    例如,以下 create 命令指定了 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 写入者角色 (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. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  3. 为您的 Google 账号创建本地身份验证凭据:

    gcloud auth application-default login

如需了解详情,请参阅 Set up authentication for a local development environment

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

查看错误报告

在 Google Cloud 控制台中,转到 Error Reporting 页面:

前往 Error Reporting

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

如需了解详情,请参阅查看错误