|
| 1 | +// Copyright 2021-2022 Workiva. |
| 2 | +// Licensed under the Apache License, Version 2.0. Please see https://github.com/Workiva/opentelemetry-dart/blob/master/LICENSE for more information |
| 3 | + |
| 4 | +import 'package:opentelemetry/api.dart'; |
| 5 | +import 'package:opentelemetry/sdk.dart' |
| 6 | + show ConsoleExporter, SimpleSpanProcessor, TracerProviderBase; |
| 7 | + |
| 8 | +void main() { |
| 9 | + final tp = TracerProviderBase( |
| 10 | + processors: [SimpleSpanProcessor(ConsoleExporter())]), |
| 11 | + tracer = tp.getTracer('instrumentation-name'); |
| 12 | + |
| 13 | + // Attach the root span to the current context (the root context) making the |
| 14 | + // span the current span until it is detached. |
| 15 | + final rootToken = Context.attach( |
| 16 | + contextWithSpan(Context.current, tracer.startSpan('root-1')..end())); |
| 17 | + |
| 18 | + // Starting a child span will automatically parent the span to the span held |
| 19 | + // by the attached context. |
| 20 | + final child1 = tracer.startSpan('child')..end(); |
| 21 | + final context = contextWithSpan(Context.current, child1); |
| 22 | + |
| 23 | + // Starting a span doesn't automatically attach the span. So to make the |
| 24 | + // parent span actually parent a span, its context needs to be attached. |
| 25 | + final childToken = Context.attach(context); |
| 26 | + tracer.startSpan('grandchild-1').end(); |
| 27 | + if (!Context.detach(childToken)) { |
| 28 | + throw Exception('Failed to detach context'); |
| 29 | + } |
| 30 | + |
| 31 | + // Alternatively, manually specifying the desired parent context avoids the |
| 32 | + // need to attach and detach the context. |
| 33 | + tracer.startSpan('grandchild-2', context: context).end(); |
| 34 | + |
| 35 | + if (!Context.detach(rootToken)) { |
| 36 | + throw Exception('Failed to detach context'); |
| 37 | + } |
| 38 | + |
| 39 | + // Since the previous root span context was detached, spans will no longer be |
| 40 | + // automatically parented. |
| 41 | + tracer.startSpan('root-2').end(); |
| 42 | +} |
0 commit comments