로그의 형식 오류

이 문서에서는 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입니다.
  • message, stack_trace 또는 exception 필드를 포함하는 jsonPayload입니다.

    두 개 이상의 필드를 지정할 수 있습니다. 두 개 이상의 필드가 지정되면 평가 순서는 stack_trace, exception, message입니다.

    오류 이벤트가 ReportedErrorEvent 객체로 형식이 지정되면 해당 필드를 jsonPayload에 복사합니다. 자세한 내용 및 예시는 ReportedErrorEvent 객체로 형식 지정된 오류 로깅을 참조하세요.

  • message, stack_trace 또는 exception 필드는 포함하지 않지만 스택 트레이스가 포함된 jsonPayload입니다.

    Error Reporting은 jsonPayload의 모든 필드에서 스택 트레이스를 검색합니다. 스택 트레이스가 두 개 이상 발견되면 스택 트레이스가 하나 선택됩니다. 선택 알고리즘은 일관된 선택을 보장합니다.

문자 메시지 로깅

텍스트 메시지인 오류 이벤트를 로깅하려면 jsonPayload에 대해 다음 형식을 사용합니다.

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

@type 필드를 지정된 값으로 설정하면 Error Reporting은 항상 모든 필수 필드가 존재하는 것처럼 로그 항목을 평가합니다. 따라서 Error Reporting은 오류 이벤트를 캡처합니다.

@type 필드를 다른 값으로 설정하거나 설정하지 않은 상태로 두면 Cloud Logging이 serviceContext 라벨 지정된 필드를 검색하여 페이로드가 ReportedErrorEvent 객체인지 확인합니다.

jsonPayloadmessage, stack_trace 또는 exception 필드에 스택 트레이스가 포함된 경우에는 @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 지원되지 않음

Examples

이 섹션에서는 로그 항목에 텍스트 메시지 또는 스택 트레이스가 포함된 경우 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)"
    ...
}