使用 OpenCensus 跟蹤 Gorm 查詢

Gorm 作爲 Go 語言中很常用的一個 ORM 庫,功能非常強大。應用程序的大量時間都花在通過 gorm 與數據庫連接上面,所以我們想在鏈路跟蹤中獲得更好的視圖。

幸運的是,Gorm 有完美的鉤子,我們可以通過 Callbacks API 將跟蹤功能注入到數據庫處理當中。Callbacks API 允許我們爲 Gorm 提供在查詢生命週期的特定部分中執行相應的函數,或者允許您在傳統的中間件方法中更改查詢行爲,或者在我們的例子中,爲可觀察性提取數據。

func beforeQuery(scope *gorm.DB) {
    // do stuff!}db.Callback().
    Create().
    Before("gorm:query").
    Register("instrumentation:before_query", beforeQuery)

這篇文章的目標是在我們的 Gorm 查詢中引入鏈路跟蹤,爲了做到這一點,我們需要同時捕獲開始和結束事件,並相應地處理鏈路信息 span。在這些例子中,我將使用 go.opencensus.io/trace 提供的跟蹤工具,它對接谷歌雲跟蹤,但其他跟蹤庫的行爲應該類似。

現在我們有一個函數在查詢開始時調用,我們需要引入鏈路追蹤:

func beforeQuery(scope *gorm.DB) {
    db.Statement.Context = startTrace(
    db.Statement.Context,
    db,
    operation,
  )
}
func startTrace(
  ctx context.Context,
  db *gorm.DB,) context.Context {
    // 判斷是否需要啓動鏈路追逐,查看追蹤的span是否存在
    if span := trace.FromContext(ctx); span == nil {
        return ctx
    }

    ctx, span := trace.StartSpan(ctx, "gorm.query")
    return ctx
}

然後我們需要對這個追蹤 span 收尾處理:

func afterQuery(scope *gorm.DB) { endTrace(scope) }func endTrace(db *gorm.DB) {
    span := trace.FromContext(db.Statement.Context)
    if span == nil || !span.IsRecordingEvents() {
        return
    }

    var status trace.Status
    if db.Error != nil {
        err := db.Error
        if err == gorm.ErrRecordNotFound {
            status.Code = trace.StatusCodeNotFound
        } else {
            status.Code = trace.StatusCodeUnknown
        }

        status.Message = err.Error()
    }
    span.SetStatus(status)
    span.End()}db.Callback().
    Query().
    After("gorm:query").
    Register("instrumentation:after_query", afterQuery)

現在我們可以在鏈路追蹤中看到所有 gorm 查詢!

然而,上圖中不太清楚查詢實際上在做什麼,讓我們看看是否可以讓這些 span 包含更多有用信息,通過添加:

查詢指紋是查詢的唯一標識符,與格式和變量無關,因此您可以唯一標識在數據庫中具有相同行爲的查詢。
讓我們擴展前面的代碼:

func startTrace(ctx context.Context, db *gorm.DB) context.Context {
    // Don't trace queries if they don't have a parent span.
    if span := trace.FromContext(ctx); span == nil {
        return ctx 
   }

    // start the span
    ctx, span := trace.StartSpan(ctx, fmt.Sprintf("gorm.query.%s", db.Statement.Table))

    // set the caller of the gorm query, so we know where in the codebase the
    // query originated.
    //
    // walk up the call stack looking for the line of code that called us. but
    // give up if it's more than 20 steps, and skip the first 5 as they're all
    // gorm anyway
    var (
        file string
        line int
    )
    for n := 5; n < 20; n++ {
        _, file, line, _ = runtime.Caller(n)
        if strings.Contains(file, "/gorm.io/") {
            // skip any helper code and go further up the call stack
            continue
        }
        break
    }
    span.AddAttributes(trace.StringAttribute("caller", fmt.Sprintf("%s:%v", file, line)))

    // add the primary table to the span metadata
    span.AddAttributes(trace.StringAttribute("gorm.table", db.Statement.Table))
    return ctx}func endTrace(db *gorm.DB) {
    // get the span from the context
    span := trace.FromContext(db.Statement.Context)
    if span == nil || !span.IsRecordingEvents() {
        return
    }

    // set the span status, so we know if the query was successful
    var status trace.Status
    if db.Error != nil {
        err := db.Error
        if err == gorm.ErrRecordNotFound {
            status.Code = trace.StatusCodeNotFound
        } else {
            status.Code = trace.StatusCodeUnknown
        }

        status.Message = err.Error()
    }
    span.SetStatus(status)

    // add the number of affected rows & query string to the span metadata
    span.AddAttributes(
        trace.Int64Attribute("gorm.rows_affected", db.Statement.RowsAffected),
        trace.StringAttribute("gorm.query", db.Statement.SQL.String()),
    )
    // Query fingerprint provided by github.com/pganalyze/pg_query_go
    fingerprint, err := pg_query.Fingerprint(db.Statement.SQL.String())
    if err != nil {
        fingerprint = "unknown"
    }

    // Rename the span with the fingerprint, as the DB handle
    // doesn't have SQL to fingerprint before being executed
    span.SetName(fmt.Sprintf("gorm.query.%s.%s", db.Statement.Table, fingerprint))

    // finally end the span
    span.End()}func afterQuery(scope *gorm.DB) {
    // now in afterQuery we can add query vars to the span metadata
    // we do this in afterQuery rather than the trace functions so we
    // can re-use the traces for non-select cases where we wouldn't want
    // to record the vars as they may contain sensitive data

    // first we extract the vars from the query & map them into a
  // human readable format
    fieldStrings := []string{}
    if scope.Statement != nil {
        fieldStrings = lo.Map(scope.Statement.Vars, func(v any i int) string {
            return fmt.Sprintf("($%v = %v)", i+1, v)
        })
    }
    // then add the vars to the span metadata
    span := trace.FromContext(scope.Statement.Context)
    if span != nil && span.IsRecordingEvents() {
        span.AddAttributes(
            trace.StringAttribute("gorm.query.vars", strings.Join(fieldStrings, ", ")),
        )
    }
    endTrace(scope)}

現在,我們獲得了非常簡單詳細的數據庫查詢跟蹤信息,使我們更容易理解我們的應用程序在做什麼!

Gorm 爲查詢生命週期的不同部分提供回調,你可以爲它們添加特定的行爲,我們目前分別跟蹤創建、刪除、更新和查詢,但如果你想更進一步,你可以查看 Gorm 文檔!. 可以在這裏 [https://gist.github.com/arussellsaw/bbedfdefee119b4600ce085b773da4b9] 找到這篇文章中的所有代碼。

請記住,如果不小心,您可能會追蹤到一些敏感數據。因此,請確保清理您的查詢變量。一個好的實踐是隻跟蹤 SELECT 查詢,因爲它們通常是通過 ID 完成的,而不是任何敏感信息。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/TdcyFzPGo6XOinXXDzgWHg