Skip to content

Commit

Permalink
Added missing log
Browse files Browse the repository at this point in the history
  • Loading branch information
Italo Vietro committed Jul 12, 2018
1 parent ea3d4c1 commit 04ca599
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
vendor/
dist/
dist/
39 changes: 39 additions & 0 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
@@ -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
}
48 changes: 48 additions & 0 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 04ca599

Please sign in to comment.