util.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package log
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime"
  6. "strconv"
  7. "sync"
  8. "go-common/library/conf/env"
  9. "go-common/library/net/metadata"
  10. "go-common/library/net/trace"
  11. )
  12. var fm sync.Map
  13. func addExtraField(ctx context.Context, fields map[string]interface{}) {
  14. if t, ok := trace.FromContext(ctx); ok {
  15. if s, ok := t.(fmt.Stringer); ok {
  16. fields[_tid] = s.String()
  17. } else {
  18. fields[_tid] = fmt.Sprintf("%s", t)
  19. }
  20. }
  21. if caller := metadata.String(ctx, metadata.Caller); caller != "" {
  22. fields[_caller] = caller
  23. }
  24. if color := metadata.String(ctx, metadata.Color); color != "" {
  25. fields[_color] = color
  26. }
  27. if cluster := metadata.String(ctx, metadata.Cluster); cluster != "" {
  28. fields[_cluster] = cluster
  29. }
  30. fields[_deplyEnv] = env.DeployEnv
  31. fields[_zone] = env.Zone
  32. fields[_appID] = c.Family
  33. fields[_instanceID] = c.Host
  34. if metadata.Bool(ctx, metadata.Mirror) {
  35. fields[_mirror] = true
  36. }
  37. }
  38. // funcName get func name.
  39. func funcName(skip int) (name string) {
  40. if pc, _, lineNo, ok := runtime.Caller(skip); ok {
  41. if v, ok := fm.Load(pc); ok {
  42. name = v.(string)
  43. } else {
  44. name = runtime.FuncForPC(pc).Name() + ":" + strconv.FormatInt(int64(lineNo), 10)
  45. fm.Store(pc, name)
  46. }
  47. }
  48. return
  49. }