diff --git a/.gitignore b/.gitignore index fd9374a..224f6c1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ vendor/ -dist/ \ No newline at end of file +dist/ diff --git a/pkg/log/log.go b/pkg/log/log.go new file mode 100644 index 0000000..7a017dc --- /dev/null +++ b/pkg/log/log.go @@ -0,0 +1,39 @@ +package log + +import ( + "context" + + "github.com/apex/log" + "github.com/apex/log/handlers/cli" +) + +type loggerKeyType int + +const loggerKey loggerKeyType = iota + +var logger *log.Logger + +func init() { + log.SetHandler(cli.Default) + if l, ok := log.Log.(*log.Logger); ok { + logger = l + } +} + +// NewContext returns a context that has a logrus logger +func NewContext(ctx context.Context) context.Context { + return context.WithValue(ctx, loggerKey, WithContext(ctx)) +} + +// WithContext returns a logrus logger from the context +func WithContext(ctx context.Context) *log.Logger { + if ctx == nil { + return logger + } + + if ctxLogger, ok := ctx.Value(loggerKey).(*log.Logger); ok { + return ctxLogger + } + + return logger +} diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go new file mode 100644 index 0000000..6dfd7e5 --- /dev/null +++ b/pkg/log/log_test.go @@ -0,0 +1,48 @@ +package log + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMiddleware(t *testing.T) { + t.Parallel() + + tests := []struct { + scenario string + function func(*testing.T) + }{ + { + scenario: "create log context", + function: testCreateLogContext, + }, + { + scenario: "create log context with nil context", + function: testCreateLogWithNilContext, + }, + } + + for _, test := range tests { + t.Run(test.scenario, func(t *testing.T) { + test.function(t) + }) + } +} + +func testCreateLogContext(t *testing.T) { + ctx := NewContext(context.Background()) + assert.NotNil(t, ctx) + + logger := WithContext(ctx) + assert.NotNil(t, logger) +} + +func testCreateLogWithNilContext(t *testing.T) { + ctx := NewContext(nil) + assert.NotNil(t, ctx) + + logger := WithContext(nil) + assert.NotNil(t, logger) +}