如何创建与请求日志的跟踪 ID 相关联的 Google Cloud Logging 条目?

huangapple go评论138阅读模式
英文:

How to create Google Cloud Logging entries that are correlated with the request log's trace ID?

问题

使用Google Cloud Logging Go客户端库,可以在Entry结构体上指定Trace字段:https://cloud.google.com/logging/docs/reference/libraries#log-entries。在Cloud Run上,默认情况下,请求会被记录并附带一个跟踪ID。我该如何获取这个跟踪ID,并在我创建的日志中指定它,以便可以通过引起日志的请求进行关联呢?

英文:

Using the Google Cloud Logging client library for go, it's possible to specify the Trace field on an Entry struct: https://cloud.google.com/logging/docs/reference/libraries#log-entries. By default, on Cloud Run, requests are logged with a trace ID. How can I get this trace ID and specify it in the logs I create so I can correlate logs by the request that caused them?

答案1

得分: 2

云运行接收到的请求会带有头部信息 X-Cloud-Trace-Context。该头部实际上是 traceID/anotherID 的格式。当你使用 cloud.google.com/go/logging 包创建一个日志 Entry 时,你需要在 Trace 字段中指定格式为 projects/{$project_id}/traces/{$trace_id} 的值,其中包括你的项目 ID 和来自头部的追踪 ID。

在我的代码中,我从请求头中获取追踪 ID,并将其设置到请求上下文 c 中,如下所示:

ctx := context.WithValue(c.Context(), logging.TraceId{}, c.Get("X-Cloud-Trace-Context"))

其中 logging 是我自定义的日志包。然后在日志代码中,我有以下方法将上下文中的追踪附加到云日志条目中:

func populateLogsEntryWithTrace(ctx context.Context, entry logging.Entry) logging.Entry {
	traceID, ok := ctx.Value(TraceId{}).(string)
	if ok {
		trace := strings.Split(traceID, "/")[0]
		entry.Trace = fmt.Sprintf("projects/%s/traces/%s", projectID, trace)
	}
	return entry
}
英文:

Requests that come in to Cloud Run will have the header X-Cloud-Trace-Context. This header is actually traceID/anotherID. When you create a logs Entry with the cloud.google.com/go/logging package, you need to specify the Trace field in the format projects/{$project_id}/traces/{$trace_id} with your project ID and the trace ID from the header.

In my code, I get the trace ID from the request header and set it on the request context c like:

ctx := context.WithValue(c.Context(), logging.TraceId{}, c.Get("X-Cloud-Trace-Context"))

where logging is my own custom logging package. Then inside logging code, I have this method to attach a trace from a context to a Cloud logging entry:

func populateLogsEntryWithTrace(ctx context.Context, entry logging.Entry) logging.Entry {
	traceID, ok := ctx.Value(TraceId{}).(string)
	if ok {
		trace := strings.Split(traceID, "/")[0]
		entry.Trace = fmt.Sprintf("projects/%s/traces/%s", projectID, trace)
	}
	return entry
}

huangapple
  • 本文由 发表于 2022年8月26日 04:10:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73493215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定