Skip to content

Commit

Permalink
logging/zap/ctxzap: add shorthand functions (#408)
Browse files Browse the repository at this point in the history
Fixes #407
  • Loading branch information
CAFxX authored Apr 9, 2021
1 parent a77ba4d commit 315ddd9
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
24 changes: 24 additions & 0 deletions logging/zap/ctxzap/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,27 @@ func ToContext(ctx context.Context, logger *zap.Logger) context.Context {
}
return context.WithValue(ctx, ctxMarkerKey, l)
}

// Debug is equivalent to calling Debug on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Debug(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Debug(msg, fields...)
}

// Info is equivalent to calling Info on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Info(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Info(msg, fields...)
}

// Warn is equivalent to calling Warn on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Warn(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Warn(msg, fields...)
}

// Error is equivalent to calling Error on the zap.Logger in the context.
// It is a no-op if the context does not contain a zap.Logger.
func Error(ctx context.Context, msg string, fields ...zap.Field) {
Extract(ctx).Error(msg, fields...)
}
51 changes: 51 additions & 0 deletions logging/zap/ctxzap/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package ctxzap

import (
"context"
"testing"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest"
)

func TestShorthands(t *testing.T) {
cases := []struct {
fn func(ctx context.Context, msg string, fields ...zapcore.Field)
level zapcore.Level
}{
{Debug, zap.DebugLevel},
{Info, zap.InfoLevel},
{Warn, zap.WarnLevel},
{Error, zap.ErrorLevel},
}
const message = "omg!"
for _, c := range cases {
t.Run(c.level.String(), func(t *testing.T) {
called := false
logger := zaptest.NewLogger(t, zaptest.WrapOptions(zap.Hooks(func(e zapcore.Entry) error {
called = true
if e.Level != c.level {
t.Fatalf("Expected %v, got %v", c.level, e.Level)
}
if e.Message != message {
t.Fatalf("message: expected %v, got %v", message, e.Message)
}
return nil
})))
ctx := ToContext(context.Background(), logger)
c.fn(ctx, message)
if !called {
t.Fatal("hook not called")
}
})
}
}

func TestShorthandsNoop(t *testing.T) {
// Just check we don't panic if there is no logger in the context.
Debug(context.Background(), "no-op")
Info(context.Background(), "no-op")
Warn(context.Background(), "no-op")
Error(context.Background(), "no-op")
}

0 comments on commit 315ddd9

Please sign in to comment.