tracing.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package tracing
  2. // Copyright 2018 Microsoft Corporation
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. import (
  16. "context"
  17. "net/http"
  18. )
  19. // Tracer represents an HTTP tracing facility.
  20. type Tracer interface {
  21. NewTransport(base *http.Transport) http.RoundTripper
  22. StartSpan(ctx context.Context, name string) context.Context
  23. EndSpan(ctx context.Context, httpStatusCode int, err error)
  24. }
  25. var (
  26. tracer Tracer
  27. )
  28. // Register will register the provided Tracer. Pass nil to unregister a Tracer.
  29. func Register(t Tracer) {
  30. tracer = t
  31. }
  32. // IsEnabled returns true if a Tracer has been registered.
  33. func IsEnabled() bool {
  34. return tracer != nil
  35. }
  36. // NewTransport creates a new instrumenting http.RoundTripper for the
  37. // registered Tracer. If no Tracer has been registered it returns nil.
  38. func NewTransport(base *http.Transport) http.RoundTripper {
  39. if tracer != nil {
  40. return tracer.NewTransport(base)
  41. }
  42. return nil
  43. }
  44. // StartSpan starts a trace span with the specified name, associating it with the
  45. // provided context. Has no effect if a Tracer has not been registered.
  46. func StartSpan(ctx context.Context, name string) context.Context {
  47. if tracer != nil {
  48. return tracer.StartSpan(ctx, name)
  49. }
  50. return ctx
  51. }
  52. // EndSpan ends a previously started span stored in the context.
  53. // Has no effect if a Tracer has not been registered.
  54. func EndSpan(ctx context.Context, httpStatusCode int, err error) {
  55. if tracer != nil {
  56. tracer.EndSpan(ctx, httpStatusCode, err)
  57. }
  58. }