Skip to content

Commit

Permalink
allow annotations for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Kleinman committed Jun 12, 2018
1 parent a4bf40f commit f2b3cbc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
1 change: 1 addition & 0 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ const (
authHandlerKey
userManagerKey
userKey
loggingAnnotationsKey
)
36 changes: 32 additions & 4 deletions middleware_grip.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,33 @@ func setServiceLogger(r *http.Request, logger grip.Journaler) *http.Request {
return r.WithContext(context.WithValue(r.Context(), loggerKey, logger))
}

type logAnnotation struct {
key string
value interface{}
}

func AddLoggingAnnotation(r *http.Request, key string, data interface{}) *http.Request {
return r.WithContext(context.WithValue(r.Context(), loggingAnnotationsKey, &logAnnotation{key: key, value: data}))
}

func setStartAtTime(r *http.Request, startAt time.Time) *http.Request {
return r.WithContext(context.WithValue(r.Context(), startAtKey, startAt))
}

func getLogAnnotation(ctx context.Context) *logAnnotation {
if rv := ctx.Value(loggingAnnotationsKey); rv != nil {
switch a := rv.(type) {
case *logAnnotation:
return a
case logAnnotation:
return &a
default:
return nil
}
}
return nil
}

func getRequestStartAt(ctx context.Context) time.Time {
if rv := ctx.Value(startAtKey); rv != nil {
if t, ok := rv.(time.Time); ok {
Expand Down Expand Up @@ -96,8 +119,8 @@ func finishLogger(logger grip.Journaler, r *http.Request, res negroni.ResponseWr
ctx := r.Context()
startAt := getRequestStartAt(ctx)
dur := time.Since(startAt)

logger.Info(message.Fields{
a := getLogAnnotation(ctx)
m := message.Fields{
"method": r.Method,
"remote": r.RemoteAddr,
"request": GetRequestID(ctx),
Expand All @@ -107,7 +130,13 @@ func finishLogger(logger grip.Journaler, r *http.Request, res negroni.ResponseWr
"status": res.Status(),
"outcome": http.StatusText(res.Status()),
"length": r.ContentLength,
})
}

if a != nil {
m[a.key] = a.value
}

logger.Info(m)
}

// This is largely duplicated from the above, but lets us optionally
Expand Down Expand Up @@ -140,7 +169,6 @@ func (l *appRecoveryLogger) ServeHTTP(rw http.ResponseWriter, r *http.Request, n
}))
}
}()

next(rw, r)

res := rw.(negroni.ResponseWriter)
Expand Down

0 comments on commit f2b3cbc

Please sign in to comment.