context.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package logging
  2. import (
  3. "context"
  4. "net/http"
  5. kitlog "github.com/go-kit/kit/log"
  6. )
  7. type logctxKeyT string
  8. // LogCTXKey is the typed context key
  9. var LogCTXKey logctxKeyT = "loggingContextKey"
  10. // NewContext helps constructing and wrapping a logger into a context
  11. func NewContext(ctx context.Context, log Interface) context.Context {
  12. return context.WithValue(ctx, LogCTXKey, log)
  13. }
  14. // FromContext extracts a logger from a context and casts to the log Interface
  15. func FromContext(ctx context.Context) Interface {
  16. v, ok := ctx.Value(LogCTXKey).(Interface)
  17. if !ok {
  18. return nil
  19. }
  20. return v
  21. }
  22. // InjectHandler injects a log instance to http.Request' context
  23. func InjectHandler(mainLog Interface) func(http.Handler) http.Handler {
  24. return func(next http.Handler) http.Handler {
  25. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  26. ctx := req.Context()
  27. if l := FromContext(ctx); l == nil {
  28. l = kitlog.With(mainLog, "urlPath", req.URL.Path)
  29. req = req.WithContext(NewContext(ctx, l))
  30. }
  31. next.ServeHTTP(w, req)
  32. })
  33. }
  34. }