如何通过 Stackdriver Logging 将错误记录到 Stackdriver Error Reporting

How to log a error to Stackdriver Error Reporting via Stackdriver Logging

我正在尝试将错误记录到 Go 中的 Stackdriver 错误报告。在错误报告的第一页上,有说明 "Reporting errors from your application can be achieved by logging application errors to Google Stackdriver Logging or..." (https://cloud.google.com/error-reporting/docs/)。我如何使用 Go 客户端库来做到这一点?

logging库提供的Entry是这样构造的:

github.com/GoogleCloudPlatform/.../logging.go#L412

type Entry struct {
    Timestamp time.Time
    Severity Severity
    Payload interface{}
    Labels map[string]string
    InsertID string
    HTTPRequest *HTTPRequest
    Operation *logpb.LogEntryOperation
    LogName string
    Resource *mrpb.MonitoredResource
}

我需要将 this JSON 结构编组到有效载荷中吗?或者我可以将堆栈跟踪作为字符串插入吗?

来自docs

// Payload must be either a string or something that
// marshals via the encoding/json package to a JSON object
// (and not any other type of JSON value).

看起来将堆栈跟踪作为字符串插入是可行的方法。

a dedicated Go package 应该可以帮助您实现这一目标:import "cloud.google.com/go/errorreporting"

您可以将其配置为通过 Stackdriver Logging 报告错误,它会负责发送正确的日志结构。