Skip to content

Commit

Permalink
Merge pull request #21 from Decentr-net/context-pr
Browse files Browse the repository at this point in the history
Added helpers to pack logger into a context
  • Loading branch information
onrik committed Mar 23, 2021
2 parents 709f97f + 59397f4 commit 89f2bfc
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
26 changes: 26 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package context

import (
"context"

"github.com/sirupsen/logrus"
)

type logCtxKey struct{}

// WithLogger puts logger into a context.
func WithLogger(parent context.Context, l logrus.FieldLogger) context.Context {
return context.WithValue(parent, logCtxKey{}, l)
}

// GetLogger returns a logger from context.
// If any logger isn't found, GetLogger returns standard instance of logrus.
func GetLogger(ctx context.Context) logrus.FieldLogger {
l, ok := ctx.Value(logCtxKey{}).(logrus.FieldLogger)
if !ok {
logrus.Debug("logger is not found in a context")
return logrus.StandardLogger()
}

return l
}
24 changes: 24 additions & 0 deletions context/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package context

import (
"bytes"
"context"
"testing"

"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)

func TestWithLogger(t *testing.T) {
l := logrus.New()
b := bytes.NewBufferString("")
l.SetOutput(b)

GetLogger(WithLogger(context.Background(), l)).Info("hi")

require.NotEmpty(t, b.String())
}

func TestGetLogger(t *testing.T) {
require.NotNil(t, GetLogger(context.Background()))
}
2 changes: 1 addition & 1 deletion filename/filename_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ func TestFilenameHook(t *testing.T) {
require.NotEqual(t, "", buff.String())
require.Equal(t,
"filename/filename_test.go:20",
gjson.Get(buff.String(), DefaultField).Str,
gjson.Get(buff.String(), "_source").Str,
)
}

0 comments on commit 89f2bfc

Please sign in to comment.