github.com/lingyao2333/mo-zero@v1.4.1/core/logx/fields.go (about)

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