github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/libkb/net_context.go (about)

     1  package libkb
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/keybase/client/go/logger"
     8  	"golang.org/x/net/context"
     9  )
    10  
    11  type withLogTagKey string
    12  
    13  func WithLogTag(ctx context.Context, k string) context.Context {
    14  	return WithLogTagWithValue(ctx, k, RandStringB64(3))
    15  }
    16  
    17  func WithLogTagWithValue(ctx context.Context, k, v string) context.Context {
    18  	ctx = logger.ConvertRPCTagsToLogTags(ctx)
    19  
    20  	addLogTags := true
    21  	tagKey := withLogTagKey(k)
    22  
    23  	if tags, ok := logger.LogTagsFromContext(ctx); ok {
    24  		if _, found := tags[tagKey]; found {
    25  			addLogTags = false
    26  		}
    27  	}
    28  
    29  	if addLogTags {
    30  		newTags := make(logger.CtxLogTags)
    31  		newTags[tagKey] = k
    32  		ctx = logger.NewContextWithLogTags(ctx, newTags)
    33  	}
    34  
    35  	// Only add a new FOO=abcdDE333EX log tag if one didn't
    36  	// already exist in this context.
    37  	if _, found := ctx.Value(tagKey).(string); !found {
    38  		ctx = context.WithValue(ctx, tagKey, v)
    39  	}
    40  	return ctx
    41  }
    42  
    43  func LogTagsToString(ctx context.Context) string {
    44  	if ctx == nil {
    45  		return ""
    46  	}
    47  
    48  	tags, ok := logger.LogTagsFromContext(ctx)
    49  	if !ok || len(tags) == 0 {
    50  		return ""
    51  	}
    52  	var out []string
    53  	for key, tag := range tags {
    54  		if v := ctx.Value(key); v != nil {
    55  			out = append(out, fmt.Sprintf("%s=%s", tag, v))
    56  		}
    57  	}
    58  	return strings.Join(out, ",")
    59  }
    60  
    61  func LogTagsFromString(tags string) map[string]string {
    62  	tagMap := make(map[string]string)
    63  	for _, tag := range strings.Split(tags, ",") {
    64  		parsedTag := strings.Split(tag, "=")
    65  		if len(parsedTag) != 2 {
    66  			continue
    67  		}
    68  		tagMap[parsedTag[0]] = parsedTag[1]
    69  	}
    70  	return tagMap
    71  }
    72  
    73  func CopyTagsToBackground(ctx context.Context) context.Context {
    74  	ret := context.Background()
    75  	if tags, ok := logger.LogTagsFromContext(ctx); ok {
    76  		ret = logger.NewContextWithLogTags(ret, tags)
    77  		for key := range tags {
    78  			if ctxKey, ok := key.(withLogTagKey); ok {
    79  				if val, ok := ctx.Value(ctxKey).(string); ok && len(val) > 0 {
    80  					ret = context.WithValue(ret, ctxKey, val)
    81  				}
    82  			}
    83  		}
    84  	}
    85  	return ret
    86  }