fields.go 697 B

123456789101112131415161718192021222324
  1. package logx
  2. import "context"
  3. var fieldsContextKey contextKey
  4. type contextKey struct{}
  5. // ContextWithFields returns a new context with the given fields.
  6. func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
  7. if val := ctx.Value(fieldsContextKey); val != nil {
  8. if arr, ok := val.([]LogField); ok {
  9. return context.WithValue(ctx, fieldsContextKey, append(arr, fields...))
  10. }
  11. }
  12. return context.WithValue(ctx, fieldsContextKey, fields)
  13. }
  14. // WithFields returns a new logger with the given fields.
  15. // deprecated: use ContextWithFields instead.
  16. func WithFields(ctx context.Context, fields ...LogField) context.Context {
  17. return ContextWithFields(ctx, fields...)
  18. }