1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2026-05-22 09:35:21 +02:00
Files
opentelemetry-go/example/namedtracer/main.go
T

80 lines
2.1 KiB
Go
Raw Normal View History

// Copyright The OpenTelemetry Authors
2019-10-22 13:19:11 -07:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"log"
2020-05-14 07:06:03 +08:00
"go.opentelemetry.io/otel/api/kv"
"go.opentelemetry.io/otel/api/correlation"
2019-11-26 12:41:24 +08:00
"go.opentelemetry.io/otel/api/global"
2019-11-01 11:40:29 -07:00
"go.opentelemetry.io/otel/api/trace"
"go.opentelemetry.io/otel/example/namedtracer/foo"
"go.opentelemetry.io/otel/exporters/trace/stdout"
2019-11-01 11:40:29 -07:00
sdktrace "go.opentelemetry.io/otel/sdk/trace"
2019-10-22 13:19:11 -07:00
)
var (
2020-05-13 16:21:23 -07:00
fooKey = kv.Key("ex.com/foo")
barKey = kv.Key("ex.com/bar")
anotherKey = kv.Key("ex.com/another")
2019-10-22 13:19:11 -07:00
)
var tp *sdktrace.Provider
// initTracer creates and registers trace provider instance.
func initTracer() {
var err error
exp, err := stdout.NewExporter(stdout.Options{})
if err != nil {
log.Panicf("failed to initialize stdout exporter %v\n", err)
return
}
tp, err = sdktrace.NewProvider(sdktrace.WithSyncer(exp),
sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}))
if err != nil {
log.Panicf("failed to initialize trace provider %v\n", err)
}
global.SetTraceProvider(tp)
2019-10-22 13:19:11 -07:00
}
func main() {
// initialize trace provider.
initTracer()
// Create a named tracer with package path as its name.
2019-11-25 18:46:07 +01:00
tracer := tp.Tracer("example/namedtracer/main")
2019-10-22 13:19:11 -07:00
ctx := context.Background()
ctx = correlation.NewContext(ctx,
2019-10-30 13:21:13 -07:00
fooKey.String("foo1"),
barKey.String("bar1"),
2019-10-22 13:19:11 -07:00
)
err := tracer.WithSpan(ctx, "operation", func(ctx context.Context) error {
2020-05-13 16:21:23 -07:00
trace.SpanFromContext(ctx).AddEvent(ctx, "Nice operation!", kv.Key("bogons").Int(100))
2019-10-22 13:19:11 -07:00
trace.SpanFromContext(ctx).SetAttributes(anotherKey.String("yes"))
2019-10-22 13:19:11 -07:00
return foo.SubOperation(ctx)
})
if err != nil {
panic(err)
}
}