Golang跟踪结束跨度早在与父跨度相同的函数中

fhity93d  于 2023-06-27  发布在  Go
关注(0)|答案(1)|浏览(89)

我有以下代码:

func handleMessage(msg Message, out chan<- string, w withdrawalSocketListener) {
    tracer := tracing.GetTracer()
    ctx, span := tracer.Start(context.Background(), "receive-withdrawal-msg-tcp-socket")
    defer func() {
        span.End()
    }()

    wr := &model.WithdrawalRequest{}

    _, unmarshallSpan := tracer.Start(ctx, "unmarshalling") // I should also End() this span after the if statement, but this if case with a return messes it up
    if err := json.Unmarshal(msg.GetBody(), wr); err != nil {
        log.Info().Err(err).Msg("failed to parse tcp inbound body")
        out <- "NACK"
        return
    }

    err := w.withdrawalService.Withdraw(wr)
    if err != nil {
        log.Info().Err(err).Msg("failed to process withdraw request")
        out <- "NACK"
        return
    }

    out <- "ACK"
}

正如你在unmarshallSpan中看到的,我想在if语句之后结束它,但是我不知道如何在它后面的if检查之后正确地停止它。我还想在withdrawalService.Withdraw函数之前启动另一个子跟踪,因此解组的另一个子跟踪应该在那里停止。我还需要return语句,这使得它有点困难。所以我的问题是,如何正确地关闭子跨度unmarshallSpan

guz6ccqo

guz6ccqo1#

这里简单的答案是调用End两次。我还建议设置跨度来表示错误:

_, unmarshallSpan := tracer.Start(ctx, "unmarshalling")
if err := json.Unmarshal(msg.GetBody(), wr); err != nil {
    log.Info().Err(err).Msg("failed to parse tcp inbound body")
    out <- "NACK"
    unmarshallSpan.RecordError(err)
    unmarshallSpan.SetStatus(codes.Error, "failed to parse tcp inbound body")
    unmarshallSpan.End()
    return
}
unmarshallSpan.End()

然而,除了最简单的情况之外,创建一个helper函数来使其可重复也是有意义的(因此您也可以对w.withdrawalService.Withdraw(wr)执行相同的操作)。例如:

func withSpan(ctx context.Context, name string, f func() error) error {
    _, s := tracing.GetTracer().Start(ctx, name)
    defer s.End()
    err := f()
    if err != nil {
        s.RecordError(err)
        s.SetStatus(codes.Error, "")
    }
    return err
}

然后,您的示例将使用withSpan,如下所示:

err := withSpan(ctx, "unmarshalling", func() error {
    return json.Unmarshal(msg.GetBody(), wr)
})
if err != nil {
    log.Info().Err(err).Msg("failed to parse tcp inbound body")
    out <- "NACK"
    return
}

相关问题