gorm.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. // Copyright 2020 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. /**
  4. * @Author: mac
  5. * @Description: gorm opentracing plugins
  6. * @Date: 2020/3/25 10:36
  7. */
  8. package trace
  9. import (
  10. "context"
  11. "fmt"
  12. "strings"
  13. "github.com/opentracing/opentracing-go/log"
  14. "github.com/jinzhu/gorm"
  15. opentracing "github.com/opentracing/opentracing-go"
  16. "github.com/opentracing/opentracing-go/ext"
  17. )
  18. const (
  19. parentSpanGormKey = "opentracingParentSpan"
  20. spanGormKey = "opentracingSpan"
  21. )
  22. // SetSpanToGorm sets span to gorm settings, returns cloned DB
  23. func SetSpanToGorm(ctx context.Context, db *gorm.DB) *gorm.DB {
  24. if ctx == nil {
  25. return db
  26. }
  27. parentSpan := opentracing.SpanFromContext(ctx)
  28. if parentSpan == nil {
  29. return db
  30. }
  31. return db.Set(parentSpanGormKey, parentSpan)
  32. }
  33. // AddGormCallbacks adds callbacks for tracing, you should call SetSpanToGorm to make them work
  34. func AddGormCallbacks(db *gorm.DB) {
  35. callbacks := newCallbacks()
  36. registerCallbacks(db, "create", callbacks)
  37. registerCallbacks(db, "query", callbacks)
  38. registerCallbacks(db, "update", callbacks)
  39. registerCallbacks(db, "delete", callbacks)
  40. registerCallbacks(db, "row_query", callbacks)
  41. }
  42. type callbacks struct{}
  43. func newCallbacks() *callbacks {
  44. return &callbacks{}
  45. }
  46. func (c *callbacks) beforeCreate(scope *gorm.Scope) { c.before(scope, "INSERT") }
  47. func (c *callbacks) afterCreate(scope *gorm.Scope) { c.after(scope, "INSERT") }
  48. func (c *callbacks) beforeQuery(scope *gorm.Scope) { c.before(scope, "SELECT") }
  49. func (c *callbacks) afterQuery(scope *gorm.Scope) { c.after(scope, "SELECT") }
  50. func (c *callbacks) beforeUpdate(scope *gorm.Scope) { c.before(scope, "UPDATE") }
  51. func (c *callbacks) afterUpdate(scope *gorm.Scope) { c.after(scope, "UPDATE") }
  52. func (c *callbacks) beforeDelete(scope *gorm.Scope) { c.before(scope, "DELETE") }
  53. func (c *callbacks) afterDelete(scope *gorm.Scope) { c.after(scope, "DELETE") }
  54. func (c *callbacks) beforeRowQuery(scope *gorm.Scope) { c.before(scope, "") }
  55. func (c *callbacks) afterRowQuery(scope *gorm.Scope) { c.after(scope, "") }
  56. func (c *callbacks) before(scope *gorm.Scope, operation string) {
  57. val, ok := scope.Get(parentSpanGormKey)
  58. if !ok {
  59. return
  60. }
  61. parentSpan := val.(opentracing.Span)
  62. tr := parentSpan.Tracer()
  63. // 如果是其他sql类型,将下面两个mysql改为对应的类型即可
  64. if operation == "" {
  65. operation = strings.ToUpper(strings.Split(scope.SQL, " ")[0])
  66. }
  67. sp := tr.StartSpan("MYSQL:"+operation, opentracing.ChildOf(parentSpan.Context()))
  68. ext.DBType.Set(sp, "mysql")
  69. scope.Set(spanGormKey, sp)
  70. }
  71. func (c *callbacks) after(scope *gorm.Scope, operation string) {
  72. val, ok := scope.Get(spanGormKey)
  73. if !ok {
  74. return
  75. }
  76. sp := val.(opentracing.Span)
  77. if operation == "" {
  78. operation = strings.ToUpper(strings.Split(scope.SQL, " ")[0])
  79. }
  80. if scope.HasError() {
  81. ext.Error.Set(sp, scope.HasError())
  82. //ext.DBStatement.Set(sp, scope.SQL)
  83. sp.LogFields(
  84. log.String("db.table", scope.TableName()),
  85. log.String("db.method", operation),
  86. log.String("db.sql", scope.SQL),
  87. log.Object("db.err", scope.DB().Error),
  88. log.Int64("db.count", scope.DB().RowsAffected),
  89. )
  90. } else {
  91. sp.LogFields(log.String("db.sql", scope.SQL),
  92. log.Int64("db.count", scope.DB().RowsAffected))
  93. }
  94. sp.Finish()
  95. }
  96. func registerCallbacks(db *gorm.DB, name string, c *callbacks) {
  97. beforeName := fmt.Sprintf("tracing:%v_before", name)
  98. afterName := fmt.Sprintf("tracing:%v_after", name)
  99. gormCallbackName := fmt.Sprintf("gorm:%v", name)
  100. // gorm does some magic, if you pass CallbackProcessor here - nothing works
  101. switch name {
  102. case "create":
  103. db.Callback().Create().Before(gormCallbackName).Register(beforeName, c.beforeCreate)
  104. db.Callback().Create().After(gormCallbackName).Register(afterName, c.afterCreate)
  105. case "query":
  106. db.Callback().Query().Before(gormCallbackName).Register(beforeName, c.beforeQuery)
  107. db.Callback().Query().After(gormCallbackName).Register(afterName, c.afterQuery)
  108. case "update":
  109. db.Callback().Update().Before(gormCallbackName).Register(beforeName, c.beforeUpdate)
  110. db.Callback().Update().After(gormCallbackName).Register(afterName, c.afterUpdate)
  111. case "delete":
  112. db.Callback().Delete().Before(gormCallbackName).Register(beforeName, c.beforeDelete)
  113. db.Callback().Delete().After(gormCallbackName).Register(afterName, c.afterDelete)
  114. case "row_query":
  115. db.Callback().RowQuery().Before(gormCallbackName).Register(beforeName, c.beforeRowQuery)
  116. db.Callback().RowQuery().After(gormCallbackName).Register(afterName, c.afterRowQuery)
  117. }
  118. }