Skip to content

Commit

Permalink
tidy
Browse files Browse the repository at this point in the history
  • Loading branch information
wbrowne committed Aug 15, 2024
1 parent 5a85003 commit 23b59b6
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions backend/log/context_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import (
"google.golang.org/grpc/metadata"
)

var loggerParamsCtxMetadataKey = "loggerParamsCtxMetadata"
const (
loggerParamsCtxMetadataKey = "loggerParamsCtxMetadata"
logParamSeparator = ":"
)

// WithContextualAttributesForOutgoingContext returns a new context with the given key/value log parameters appended to the existing ones.
// It's possible to get a logger with those contextual parameters by using [FromContext].
// WithContextualAttributesForOutgoingContext will append the given key/value log parameters to the outgoing context.
func WithContextualAttributesForOutgoingContext(ctx context.Context, logParams []any) context.Context {
if len(logParams) == 0 || len(logParams)%2 != 0 {
return ctx
Expand All @@ -20,24 +22,23 @@ func WithContextualAttributesForOutgoingContext(ctx context.Context, logParams [
for i := 0; i < len(logParams); i += 2 {
k := logParams[i].(string)
v := logParams[i+1].(string)
ctx = metadata.AppendToOutgoingContext(ctx, loggerParamsCtxMetadataKey, fmt.Sprintf("%s:%s", k, v))
ctx = metadata.AppendToOutgoingContext(ctx, loggerParamsCtxMetadataKey, fmt.Sprintf("%s%s%s", k, logParamSeparator, v))
}

return ctx
}

// ContextualAttributesFromIncomingContext returns the contextual key/value log parameters from the given context.
// If no contextual log parameters are set, it returns nil.
// ContextualAttributesFromIncomingContext returns the contextual key/value log parameters from the given incoming context.
func ContextualAttributesFromIncomingContext(ctx context.Context) []any {
logParams := metadata.ValueFromIncomingContext(ctx, loggerParamsCtxMetadataKey)
if len(logParams) == 0 {
return nil
}

var res []any
var attrs []any
for _, param := range logParams {
kv := strings.Split(param, ":")
res = append(res, kv[0], kv[1])
kv := strings.Split(param, logParamSeparator)
attrs = append(attrs, kv[0], kv[1])
}
return res
return attrs
}

0 comments on commit 23b59b6

Please sign in to comment.