gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package db
  4. import (
  5. "context"
  6. "time"
  7. "code.gitea.io/gitea/modules/gtprof"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/setting"
  10. "xorm.io/xorm/contexts"
  11. )
  12. type EngineHook struct {
  13. Threshold time.Duration
  14. Logger log.Logger
  15. }
  16. var _ contexts.Hook = (*EngineHook)(nil)
  17. func (*EngineHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
  18. ctx, _ := gtprof.GetTracer().Start(c.Ctx, gtprof.TraceSpanDatabase)
  19. return ctx, nil
  20. }
  21. func (h *EngineHook) AfterProcess(c *contexts.ContextHook) error {
  22. span := gtprof.GetContextSpan(c.Ctx)
  23. if span != nil {
  24. // Do not record SQL parameters here:
  25. // * It shouldn't expose the parameters because they contain sensitive information, end users need to report the trace details safely.
  26. // * Some parameters contain quite long texts, waste memory and are difficult to display.
  27. span.SetAttributeString(gtprof.TraceAttrDbSQL, c.SQL)
  28. span.End()
  29. } else {
  30. setting.PanicInDevOrTesting("span in database engine hook is nil")
  31. }
  32. if c.ExecuteTime >= h.Threshold {
  33. // 8 is the amount of skips passed to runtime.Caller, so that in the log the correct function
  34. // is being displayed (the function that ultimately wants to execute the query in the code)
  35. // instead of the function of the slow query hook being called.
  36. h.Logger.Log(8, &log.Event{Level: log.WARN}, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime)
  37. }
  38. return nil
  39. }