github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/log/context.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type (
     8  	ctxLevelKey struct{}
     9  	ctxNamesKey struct{}
    10  )
    11  
    12  func WithLevel(ctx context.Context, lvl Level) context.Context {
    13  	return context.WithValue(ctx, ctxLevelKey{}, lvl)
    14  }
    15  
    16  func LevelFromContext(ctx context.Context) Level {
    17  	v, _ := ctx.Value(ctxLevelKey{}).(Level)
    18  
    19  	return v
    20  }
    21  
    22  func WithNames(ctx context.Context, names ...string) context.Context {
    23  	// trim capacity for force allocate new memory while append and prevent data race
    24  	oldNames := NamesFromContext(ctx)
    25  	oldNames = oldNames[:len(oldNames):len(oldNames)]
    26  
    27  	return context.WithValue(ctx, ctxNamesKey{}, append(oldNames, names...))
    28  }
    29  
    30  func NamesFromContext(ctx context.Context) []string {
    31  	v, _ := ctx.Value(ctxNamesKey{}).([]string)
    32  	if v == nil {
    33  		return []string{}
    34  	}
    35  
    36  	return v[:len(v):len(v)] // prevent re
    37  }
    38  
    39  func with(ctx context.Context, lvl Level, names ...string) context.Context {
    40  	return WithLevel(WithNames(ctx, names...), lvl)
    41  }