登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-02 22:09:35 199浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《如何将自定义跟踪添加到 Go 中的第二代 App Engine 应用程序?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

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

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


解决方案


关键是我缺少的是理解跨度上下文如何传递到服务应用程序。 google 利用 x-cloud-trace-context 标头在发送到服务实例的请求中传播跨度上下文,并且 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!")
}

好了,本文到此结束,带大家了解了《如何将自定义跟踪添加到 Go 中的第二代 App Engine 应用程序?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>