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

您可以使用 Java 版 Error Reporting 软件包,从 Java 应用向 Error Reporting 发送错误报告。

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

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

须知事项

  1. 登录您的 Google Cloud 帐号。如果您是 Google Cloud 新手,请创建一个帐号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

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

  4. 启用 Error Reporting API 。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

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

  7. 启用 Error Reporting API 。

    启用 API

安装客户端库

借助 Java 版 Error Reporting 软件包,您可以监控和查看几乎在任何位置运行的 Java 应用所报告的错误。

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

配置客户端库

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

报告错误

仅在需要报告自定义错误事件时,才使用 Java 版 Error Reporting 程序包。

使用 Cloud Logging Logback Appenderjava.util.logging Handler 记录的异常会自动报告给 Error Reporting 控制台。

以下示例演示了如何使用 API 报告自定义错误事件:

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 参考文档

在 Google Cloud 上运行

要使用 Java 版 Error Reporting 软件包,您必须具备 Identity and Access ManagementError Reporting Writer 角色。大多数 Google Cloud 计算平台均默认提供此角色。

您可以使用以下 Google Cloud 环境配置 Java 版 Error Reporting。

App Engine 柔性环境

App Engine 默认授予 Error Reporting 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

GKE 上,您必须在创建集群时添加 cloud-platform 访问权限范围,如以下示例命令所示:

gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/cloud-platform

Compute Engine

使用 Compute Engine 虚拟机实例时,请为每个实例添加 cloud-platform 访问权限范围。通过 Google Cloud 控制台创建新实例时,您可以在创建实例面板的身份和 API 访问权限部分执行此操作。请使用 Compute Engine 默认服务账号或您选用的其他服务账号,并在身份和 API 访问权限部分中勾选允许所有 Cloud API 的全面访问权限。无论您选择哪个服务帐号,都请确保已在 Google Cloud 控制台的 IAM 和管理部分中向该服务帐号授予 Error Reporting 写入者角色

在本地和其他位置运行

如需在 Google Cloud 之外(包括您自己的工作站、您数据中心的计算机或另一家云提供商的虚拟机实例上)使用 Java 版 Error Reporting 软件包,您必须直接向 Java 版 Error Reporting 软件包提供您的 Google Cloud 项目 ID 和相应的服务账号凭据。

您可以手动创建和获取服务账号凭据。指定角色字段时,请使用 Error Reporting Writer 角色。如需详细了解 Identity and Access Management 角色,请转到访问权限控制指南

查看错误报告

在 Google Cloud 控制台中,选择 Error Reporting,或点击以下按钮,然后选择项目:

转到 Error Reporting

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