登录
首页 >  Golang >  Go问答

跟踪 golang http 请求

来源:stackoverflow

时间:2024-03-04 17:36:25 109浏览 收藏

今天golang学习网给大家带来了《跟踪 golang http 请求》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我想在 golang 中跟踪 http 请求的完整执行。对于任何重要的操作,请求最终都会调用许多不同的函数。我希望整个执行堆栈中的日志都标有唯一的请求 id。例如

http.handle("/my-request", myrequesthandler)
func myrequesthandler(w http.responsewriter, r *http.request) {

        //debug print1
        log.printf("....")
        myfunc()
}

func myfunc() {
        //debug print2
        log.printf("....")
}

这里我需要一种方法来将 print1 和 print2 识别为同一请求的一部分。看起来 zerolog 确实有类似的东西,如此处所述。就像这样:

....
c = c.Append(hlog.RequestIDHandler("req_id", "Request-Id"))
h := c.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   
    hlog.FromRequest(r).Info().
        Msg("Something happened")

}))
http.Handle("/", h)

但是如果我理解正确的话,它将涉及将请求对象传递给每个函数。这是解决这个问题的惯用方法吗?有哪些替代方案?


正确答案


收到请求后立即在 context.Context 上设置一个唯一 id,并将该上下文传递到调用堆栈。这就是上下文的用途。

[context] 跨 api 边界和进程之间携带截止日期、取消信号、和其他请求范围的值

示例:

// you could place this in a separate helper package to improve encapsulation
type ctxkey struct{}

func myrequesthandler(w http.responsewriter, r *http.request) {
    uniqueid := // generate a unique identifier 

    // create a context with the http.request context as parent
    ctx := context.withvalue(r.context(), ctxkey{}, uniqueid)
    
    foo(ctx, ...)
    bar(ctx, ...)
}

func foo(ctx context.context, ...) {
    uniqueid := ctx.value(ctxkey{})
    // do something with the unique id
    baz(ctx, ...)
}

特别是:

  • 创建以 *http.request.context() 作为父级的上下文。这样,如果请求被取消,例如由于客户端断开连接,取消操作将传播到您的子上下文
  • 考虑使用未导出的结构作为键来设置上下文值。包中定义的未导出结构永远不会与其他键冲突。如果您使用字符串作为键,则理论上任何包都可以使用相同的键并覆盖您的值(或者您可以覆盖其他值)。 ymmv。
  • 按照包文档的建议,将上下文作为调用堆栈中任何函数的第一个参数传递。

对于跨应用程序的跟踪和日志记录,您可能需要查看 opentracing。如上所述,跟踪器的传播仍然通过 contexts 完成。

您可以使用 context.context 并通过以下方式在其上设置请求 id中间件功能。
示例:

type requestidkey struct{}

func requestidsetter(next http.handlerfunc) http.handlerfunc {
    return func(rw http.responsewriter, r *http.request) {
        // use provided request id from incoming request if any
        reqid := r.header.get("x-request-id")
        if reqid == "" {
            // or use some generated string
            reqid = uuid.new().string()
        }
        ctx := context.withvalue(r.context(), requestidkey{}, reqid)

        next(rw, r.withcontext(ctx))
    }
}

然后您需要修改记录器以接受 context.context
示例:

func printfwithcontext(ctx context.context, format string, v ...interface{}) {
    reqid := ctx.value(requestidkey{}).(string)
    log.printf(reqid+": "+format, v...)
}

最后应用到您的代码

http.HandleFunc("/my-request", requestIDSetter(myrequestHandler))

func myrequestHandler(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    //debug print1
    printfWithContext(ctx, "....1")
    myfunc(ctx)
}

func myfunc(ctx context.Context) {
    //debug print2
    printfWithContext(ctx, "....2")
}

本篇关于《跟踪 golang http 请求》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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