google-app-engine - 如何将自定义跟踪添加到 Go 中的第二代 App Engine 应用程序?

标签 google-app-engine go trace google-cloud-stackdriver

Google App Engine 现在通过新的 second-generation 支持 Go 1.11标准环境。在将较旧的标准环境应用程序转换为第二代时,如何将应用程序引擎基础架构中的跟踪信息与我使用 OpenCensus 添加到应用程序中的自定义跟踪相结合并不明显。 .

尽管我已经创建了 stackdriver 导出器并注册了跟踪,但我没有在附加到入站请求的 stackdriver 控制台中看到自定义跟踪信息。

最佳答案

关键是我缺少的是理解跨度上下文如何传递到服务应用程序。 Google 利用 X-Cloud-Trace-Context header 在发送到服务实例的请求中传播跨度上下文,并且 go.opencensus.io/exporter/stackdriver/propagation库提供了在 http 请求中提取和保留此信息的实现。

别忘了create a stackdriver exporter ,并注册其踪迹。导出器库的文档显示了这样的示例。

// CreateSpanFromRequest returns a context and span based on the http.Request.
// If no existing spancontext is found, this will start a new span.
// Modifies existing request to contain the generated span's context.
func CreateSpanFromRequest(name string, r *http.Request) (context.Context, *trace.Span) {
    var span *trace.Span
    ctx := r.Context()
    httpFormat := &propagation.HTTPFormat{}
    sc, ok := httpFormat.SpanContextFromRequest(r)
    if ok {
        ctx, span = trace.StartSpanWithRemoteParent(ctx, name, sc)
    } else {
        ctx, span = trace.StartSpan(ctx, name)
    }
    // Write the span context into the http.Request.  We do this to
    // to enable chaining handlers together more easily.
    httpFormat.SpanContextToRequest(span.SpanContext(), r)
    return ctx, span
}

使用它,我能够将自定义跨度添加到我的处理程序中,这些处理程序将与 stackdriver 中的传入请求信息正确关联:

func indexHandler(w http.ResponseWriter, r *http.Request) {
    _, span := CreateSpanFromRequest("indexHandler", r)
    defer span.End()
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }
    fmt.Fprint(w, "Hello, World!")
}

关于google-app-engine - 如何将自定义跟踪添加到 Go 中的第二代 App Engine 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52935944/

相关文章:

python - Python 中的异常处理(webapp2、Google App Engine)

unit-testing - 在单元测试中使用 webapp2 i18n

google-app-engine - Google App 脚本/Gmail 附加组件 : How to display a window with text and buttons over Gmail?

java - JWT验证失败: BAD_SIGNATURE

go - 如何在 Golang 中使用其他文件中的其他结构方法

linux - golang应用如何启动upstart进程?

go - 在 golang 中,如何从函数内重新分配外部引用?

c# - 如何在 Visual Studio IDE C# 中隐藏跟踪代码?

Haskell 跟踪函数

oracle - 查询 Oracle 运行 sql 和绑定(bind)变量的值