fields.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package logx
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. )
  7. var (
  8. fieldsContextKey contextKey
  9. globalFields atomic.Value
  10. globalFieldsLock sync.Mutex
  11. )
  12. type contextKey struct{}
  13. // AddGlobalFields adds global fields.
  14. func AddGlobalFields(fields ...LogField) {
  15. globalFieldsLock.Lock()
  16. defer globalFieldsLock.Unlock()
  17. old := globalFields.Load()
  18. if old == nil {
  19. globalFields.Store(append([]LogField(nil), fields...))
  20. } else {
  21. globalFields.Store(append(old.([]LogField), fields...))
  22. }
  23. }
  24. // ContextWithFields returns a new context with the given fields.
  25. func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
  26. if val := ctx.Value(fieldsContextKey); val != nil {
  27. if arr, ok := val.([]LogField); ok {
  28. return context.WithValue(ctx, fieldsContextKey, append(arr, fields...))
  29. }
  30. }
  31. return context.WithValue(ctx, fieldsContextKey, fields)
  32. }
  33. // WithFields returns a new logger with the given fields.
  34. // deprecated: use ContextWithFields instead.
  35. func WithFields(ctx context.Context, fields ...LogField) context.Context {
  36. return ContextWithFields(ctx, fields...)
  37. }