Create a gist now

Instantly share code, notes, and snippets.

@burke /foo.go Secret
Created Mar 8, 2018

Embed
package main
import (
"context"
"errors"
log "github.com/sirupsen/logrus"
)
type someContextKey string
var (
keyA = someContextKey("a")
keyB = someContextKey("b")
)
func main() {
ctx := context.Background()
ctx = context.WithValue(ctx, keyA, "foo")
ctx = context.WithValue(ctx, keyB, "bar")
log2(ctx, nil).Info("did nothing")
err := errors.New("an error")
log2(ctx, err).Fatal("unrecoverable error")
}
func log2(ctx context.Context, err error) *log.Entry {
entry := log.WithField("component", "main")
if err != nil {
entry = entry.WithField("error", err)
}
if a := ctx.Value(keyA); a != nil {
entry = entry.WithField("a", a)
}
if b := ctx.Value(keyB); b != nil {
entry = entry.WithField("b", b)
}
return entry
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment