ログでエラーをフォーマットする

このドキュメントでは、Cloud Logging を使用してエラーイベントを報告するときにログエントリをフォーマットする方法について説明します。

Cloud Logging API メソッド write または Error Reporting API メソッド report を実行することで、Google Cloud プロジェクトにエラーイベントを報告できます。Cloud Logging API を使用してエラーイベントを報告する場合、リクエストの本文に、スタック トレースを含む LogEntry オブジェクトまたは ReportedErrorEvent オブジェクトが含まれます。

始める前に

  • ご使用の言語とプラットフォームの設定手順に従ってください。

  • API キーベースの認証が必要な場合は、Error Reporting API を使用する必要があります。Error Reporting API を使用してエラーイベントを報告するには、メソッド report を実行して、メソッドのリクエスト本文を ReportedErrorEvent オブジェクトとしてフォーマットします。

    Error Reporting API を使用すると、正しい形式のエラー メッセージを含むログエントリが自動的に生成され、Cloud Logging に書き込まれます。これらのログエントリは、次のような logName の形式のログに書き込まれます。

    projects/PROJECT_ID/clouderrorreporting.googleapis.com%2Freported_errors
    

    ログエントリは report の呼び出しによって生成されるため、Cloud Logging の取り込み料金が発生することがあります。取り込むログを指定するには、除外フィルタをご覧ください。

    Error Reporting API を使用してエラーイベントを報告した場合、このドキュメントの残りの部分は適用されません。

LogEntry 形式の要件

このセクションでは、ログエントリに含まれるエラーイベントを Error Reporting がキャプチャするように、LogEntry をフォーマットする方法について説明します。

スタック トレースをログに記録する

スタック トレースであるエラーイベントをログに記録するには、エラーイベントを次のいずれかのタイプとして記述します。

  • 複数行の textPayload
  • messagestack_traceexception フィールドを含む jsonPayload

    これらのフィールドは複数指定できます。これらのフィールドが複数指定されている場合、評価は stack_traceexceptionmessage の順で行われます。

    エラーイベントが ReportedErrorEvent オブジェクトとしてフォーマットされている場合は、そのフィールドを jsonPayload にコピーします。詳細と例については、ReportedErrorEvent オブジェクトとしてフォーマットされたエラーをログに記録するをご覧ください。

  • messagestack_traceexception フィールドを含まないが、スタック トレースが含まれる jsonPayload

    Error Reporting は、jsonPayload 内のすべてのフィールドからスタック トレースを検索します。複数のスタック トレースが見つかった場合は、1 つのスタック トレースが選択されます。選択アルゴリズムによって、一貫性のある選択が可能になります。

テキスト メッセージをログに記録する

テキスト メッセージのエラーイベントをログに記録するには、jsonPayload に次の形式を使用します。

    "jsonPayload": {
      "@type": "type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent",
      "message": "Text message"
    },

@type フィールドに指定された値を設定すると、Error Reporting は常にすべての必須フィールドが存在するものとしてログエントリを評価します。その結果、Error Reporting はエラーイベントを取得します。

@type フィールドに別の値を設定するか、未設定の場合、Cloud Logging は serviceContext というラベルの付いたフィールドを検索して、ペイロードが ReportedErrorEvent オブジェクトかどうかを判断します。

jsonPayloadmessagestack_traceexception フィールドにスタック トレースが含まれている場合、@type フィールドを設定する必要はありません。その場合、Error Reporting は自動的にエラーイベントを取得します。

サポートされるモニタリング対象リソース

LogEntry オブジェクトの resource フィールドを、サポートされている次のモニタリング対象リソースタイプのいずれかに設定します。

  • app_script_function
  • aws_ec2_instance
  • cloud_function
  • cloud_run_jobs
  • cloud_run_revision
  • consumed_api
  • container
  • dataflow_step
  • gae_app
  • gce_instance
  • k8s_container
  • k8s_pod
  • ml_job1
  • workflows.googleapis.com/Workflow
  • global1

1 textPayload はサポートされません

このセクションでは、ログエントリにテキスト メッセージまたはスタック トレースが含まれている場合に、Error Reporting がログエントリを処理するようにする方法について説明します。

テキスト メッセージのエラーイベントをログに記録する

次の例は、テキスト メッセージのエラーイベントを記録する場合に LogEntry オブジェクトをフォーマットする方法を示しており、LogEntryjsonPayload フィールドに次の JSON 構造を使用します。

{...
  {
    "jsonPayload": {
      "@type": "type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent",
      "message": "A simple text message"
    },
    "logName": "projects/test-project/logs/reported-error",
    "resource": {
      "labels": {
        "project_id": "test-project"
      },
      "type": "global"
    },
    "severity": "ERROR",
    "timestamp": "2019-06-27T13:43:26.375834551Z"
  }
}

この例に示すように、@type フィールドを、Error Reporting にログエントリをグループ化する値に設定する必要があります。詳細については、テキスト メッセージをログに記録するをご覧ください。

message フィールドにスタック トレースが含まれている場合、ログエントリは自動的にグループ化されるため、@type フィールドを指定する必要はありません。

ReportedErrorEvent オブジェクトとしてフォーマットされたエラーをログに記録する

エラーイベントが ReportedErrorEvent オブジェクトに保存される場合、LogEntryjsonPayload フィールドに次の JSON 構造を使用します。

{
  "eventTime": string,
  "serviceContext": {
    "service": string,     // Required.
    "version": string
  },
  "message": string,       // Required. This field contains the main error content to report.
  "@type": string          // Optional. For information about this field, see Log a text message.
  "context": {
    "httpRequest": {
      "method": string,
      "url": string,
      "userAgent": string,
      "referrer": string,
      "responseStatusCode": number,
      "remoteIp": string
    },
    "user": string,
    "reportLocation": {    // Required if no stack trace is provided.
      "filePath": string,
      "lineNumber": number,
      "functionName": string
    }
  }
}

message フィールドにエラー情報を必ず入力してください。スタック トレースを ReportedErrorEvent オブジェクトの message フィールドに保存するには、詳細については、report メソッドのリファレンス ページをご覧ください。

次の例では、LogEntryjsonPayload フィールドを ReportedErrorEvent オブジェクトとしてフォーマットするように設定する方法を示します。message フィールドにはスタック トレースが含まれているため、エラーイベントは Error Reporting によってグループ化されます。

{...
   "jsonPayload": {
      "serviceContext": {
        "service": "frontend",
        "version": "bf6b5b09b9d3da92c7bf964ab1664fe751104517"
      },
      "message": "com.example.shop.Template$CartDiv retrieveCart: Error\njava.lang.IndexOutOfBoundsException: Index: 4, Size: 4\n\tat java.util.ArrayList.rangeCheck(ArrayList.java:635)\n\tat java.util.ArrayList.get(ArrayList.java:411)\n\tat com.example.shop.Cart.retrieve(Cart.java:76)\n\tat com.example.shop.Cart.generate(Cart.java:55)\n\tat com.example.shop.Template$CartDiv.retrieveCart(Template.java:113)\n\tat com.example.shop.Template.generate(Template.java:22)\n\tat com.example.shop.CartServlet.doGet(CartServlet.java:115)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:717)\n",
      "context":
        "httpRequest": {
          "method": "GET",
          "url": "http://example.com/shop/cart",
          "responseStatusCode": 500
        },
        "user": "9f32f587135aa6774e78ed30fbaabcce3ec5528f"
      }
   },
   "logName": "projects/test-project/logs/reported-error",
   "resource": {
      "labels": {
        "project_id": "test-project"
      },
      "type": "global"
   },
   "severity": "ERROR",
   "timestamp": "2019-06-27T13:43:26.375834551Z"
}

textPayload フィールドを使用してエラーイベントを記録する

エラーイベントを記録するには、LogEntrytextPayload フィールドを使用してエラーデータを保存します。たとえば、次の Google Cloud CLI コマンドは、重大度が ERROR で、textPayload フィールドにエラーイベントが含まれるログエントリになります。

gcloud logging write test-log --severity=ERROR --payload-type=text 'RuntimeException: Oops! Something bad happened.
at com.example.MyClass.method(MyClass.java:123)
at com.example.OtherClass.doStuff(Unknown Source)
at com.example.Sys.create(Native Method)'

上記のコマンドの結果は、Error Reporting でグループ化されたログエントリになります。

{...
    logName: "projects/PROJECT_ID/logs/test-log"
    severity: "ERROR"
    textPayload: "RuntimeException: Oops! Something bad happened.
                  at com.example.MyClass.method(MyClass.java:123)
                  at com.example.OtherClass.doStuff(Unknown Source)
                  at com.example.Sys.create(Native Method)"
    ...
}