Error Reporting 用の Java アプリのインストルメント化

Java アプリケーションから Error Reporting にエラーレポートを送信するには、Java 用 Error Reporting パッケージを使用します。 Java 用 Error Reporting パッケージを使用して、次の場合にエラーグループを作成します。

  • ログバケットには顧客管理の暗号鍵(CMEK)が含まれています。
  • ログバケットが global リージョンにない
  • カスタム エラーイベントを報告する。

Error Reporting は、App EngineCompute EngineGoogle Kubernetes Engine などの一部の Google Cloud サービスに統合されています。Error Reporting は、こうしたサービスで実行されるアプリケーションによって Cloud Logging に記録されたエラーを表示します。詳細については、このページの Google Cloud での実行をご覧ください。

Logging を使用して、エラーデータを Error Reporting に送信することもできます。データ形式の要件については、Logging のエラー メッセージの形式設定をご覧ください。

準備

  1. Google Cloud アカウントにログインします。Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $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 リファレンス ドキュメントをご覧ください。

Google Cloud でアプリを実行する

projects.events.report を使用してエラーグループを作成するには、サービス アカウントに Error Reporting 書き込みロールroles/errorreporting.writer)が必要です。

一部の Google Cloud サービスでは、Error Reporting 書き込みロール(roles/errorreporting.writer)が適切なサービス アカウントに自動的に付与されます。ただし、一部のサービスに適したサービス アカウントにこのロールを付与する必要があります。

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 アクセス スコープを付与します。

    たとえば、次の create コマンドでは、cloud-platform アクセス スコープとサービス アカウントを指定します。

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

Compute Engine

Compute Engine の VM インスタンスで Error Reporting を使用するには、次のようにします。

  1. VM インスタンスが使用するサービス アカウントに、Error Reporting 書き込みロールroles/errorreporting.writer)が付与されていることを確認します。

    Compute Engine のデフォルトのサービス アカウントまたはカスタム サービス アカウントを使用できます。

    ロールの付与については、プロジェクト、フォルダ、組織へのアクセスを管理するをご覧ください。

  2. Google Cloud コンソールのナビゲーション パネルで、[Compute Engine] を選択してから、[VM インスタンス] を選択します。

    [VM インスタンス] に移動

  3. cloud-platform アクセス スコープを受け取る VM インスタンスを選択します。

  4. [停止]、[編集] の順にクリックします。

  5. [ID と API へのアクセス] セクションで、Error Reporting 書き込みロール(roles/errorreporting.writer)を持つサービス アカウントを選択します。

  6. [アクセス スコープ] セクションで、[すべての Cloud API に完全アクセス権を許可] を選択して、変更内容を保存します。

  7. [開始 / 再開] をクリックします。

Cloud Logging Logback Appenderjava.util.logging Handler を使用して記録された例外は、Error Reporting Console に自動的に報告されます。

次のサンプルは、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

詳細については、 ローカル開発環境の認証の設定 をご覧ください。

projects.events.report メソッドは API キーもサポートしています。 認証に API キーを使用する場合、ローカルのアプリケーションのデフォルト認証情報ファイルを設定する必要はありません。詳細については、Google Cloud の認証に関するドキュメントの API キーを作成するをご覧ください。

エラーレポートの表示

Google Cloud コンソールのナビゲーション パネルで [エラーレポート] を選択し、Google Cloud プロジェクトを選択します。

Error Reporting に移動

詳細については、エラーの表示をご覧ください。