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