-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #21 from Decentr-net/context-pr
Added helpers to pack logger into a context
- Loading branch information
Showing
3 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters