Skip to content

Commit

Permalink
Create a ContextWithLogger function (#14)
Browse files Browse the repository at this point in the history
Turns out I need to add loggers to contexts outside ths package.

logrus is apparently normally called Sirupsen/logrus, not sirupsen/logrus.
  • Loading branch information
richvdh committed Sep 29, 2017
1 parent 466baca commit cf7e2e3
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -4,7 +4,7 @@ go:
install:
- go get github.com/golang/lint/golint
- go get github.com/fzipp/gocyclo
- go get github.com/sirupsen/logrus
- go get github.com/Sirupsen/logrus
- go get github.com/mattn/goveralls
script:
- ./hooks/pre-commit
Expand Down
7 changes: 6 additions & 1 deletion context.go
Expand Up @@ -3,7 +3,7 @@ package util
import (
"context"

log "github.com/sirupsen/logrus"
log "github.com/Sirupsen/logrus"
)

// contextKeys is a type alias for string to namespace Context keys per-package.
Expand Down Expand Up @@ -35,3 +35,8 @@ func GetLogger(ctx context.Context) *log.Entry {
}
return l.(*log.Entry)
}

// ContextWithLogger creates a new context, which will use the given logger.
func ContextWithLogger(ctx context.Context, l *log.Entry) context.Context {
return context.WithValue(ctx, ctxValueLogger, l)
}
4 changes: 2 additions & 2 deletions json.go
Expand Up @@ -8,7 +8,7 @@ import (
"runtime/debug"
"time"

log "github.com/sirupsen/logrus"
log "github.com/Sirupsen/logrus"
)

// JSONResponse represents an HTTP response which contains a JSON body.
Expand Down Expand Up @@ -99,7 +99,7 @@ func Protect(handler http.HandlerFunc) http.HandlerFunc {
func RequestWithLogging(req *http.Request) *http.Request {
reqID := RandomString(12)
// Set a Logger and request ID on the context
ctx := context.WithValue(req.Context(), ctxValueLogger, log.WithFields(log.Fields{
ctx := ContextWithLogger(req.Context(), log.WithFields(log.Fields{
"req.method": req.Method,
"req.path": req.URL.Path,
"req.id": reqID,
Expand Down
2 changes: 1 addition & 1 deletion json_test.go
Expand Up @@ -7,7 +7,7 @@ import (
"net/http/httptest"
"testing"

log "github.com/sirupsen/logrus"
log "github.com/Sirupsen/logrus"
)

type MockJSONRequestHandler struct {
Expand Down

0 comments on commit cf7e2e3

Please sign in to comment.