Skip to content

Commit

Permalink
add GetField func to get an specific field from logger (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuseferi committed Jan 17, 2024
1 parent aa57e19 commit 7495cf4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -27,6 +27,9 @@ To retrieve stored zap fields in context and log them :

logger.With(zax.Get(ctx)...).Info("just a test record")

To retrieve an specific field in the context you can use zax.GetField:

zax.GetField(ctx, "trace_id")

After that, you can use the output as a regular logger and perform logging operations:

Expand Down
12 changes: 12 additions & 0 deletions zax.go
Expand Up @@ -34,3 +34,15 @@ func Get(ctx context.Context) []zap.Field {
}
return nil
}

// GetField Get a specific zap stored field from context by key
func GetField(ctx context.Context, key string) (field zap.Field) {
if loggerFields, ok := ctx.Value(loggerKey).([]zap.Field); ok {
for _, field := range loggerFields {
if field.Key == key {
return field
}
}
}
return
}
25 changes: 25 additions & 0 deletions zax_test.go
Expand Up @@ -162,3 +162,28 @@ func TestGet(t *testing.T) {
})
}
}
func TestGetField(t *testing.T) {
traceIDKey := traceIDKey
ctx := context.Background()
tests := map[string]struct {
context context.Context
expectedValue string
}{
"context empty": {
context: context.TODO(),
expectedValue: "",
},
"context with trace-id field": {
context: Set(ctx, []zap.Field{zap.String(traceIDKey, testTraceID)}),
expectedValue: testTraceID,
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := tc.context
field := GetField(ctx, traceIDKey)
assert.Equal(t, tc.expectedValue, field.String)
})
}
}

0 comments on commit 7495cf4

Please sign in to comment.