Debian Codegraph @

exporters/stdout/stdouttrace/trace.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package stdouttrace // import "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
5
6 import (
7 "context"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "sync"
12 "time"
13
14 "go.opentelemetry.io/otel/exporters/stdout/stdouttrace/internal/counter"
15 "go.opentelemetry.io/otel/exporters/stdout/stdouttrace/internal/observ"
16 "go.opentelemetry.io/otel/sdk/trace"
17 "go.opentelemetry.io/otel/sdk/trace/tracetest"
18 )
19
20 var zeroTime time.Time
21
22 var _ trace.SpanExporter = &Exporter{}
23
24 // New creates an Exporter with the passed options.
25 func New(options ...Option) (*Exporter, error) {
26 cfg := newConfig(options...)
27
28 enc := json.NewEncoder(cfg.Writer)
29 if cfg.PrettyPrint {
30 enc.SetIndent("", "\t")
31 }
32
33 exporter := &Exporter{
34 encoder: enc,
35 timestamps: cfg.Timestamps,
36 }
37
38 var err error
39 exporter.inst, err = observ.NewInstrumentation(counter.NextExporterID())
40 return exporter, err
41 }
42
43 // Exporter is an implementation of trace.SpanSyncer that writes spans to stdout.
44 type Exporter struct {
45 encoder *json.Encoder
46 encoderMu sync.Mutex
47 timestamps bool
48
49 stoppedMu sync.RWMutex
50 stopped bool
51
52 inst *observ.Instrumentation
53 }
54
55 // ExportSpans writes spans in json format to stdout.
56 func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) (err error) {
57 var success int64
58 if e.inst != nil {
59 op := e.inst.ExportSpans(ctx, len(spans))
60 defer func() { op.End(success, err) }()
61 }
62
63 if err := ctx.Err(); err != nil {
64 return err
65 }
66 e.stoppedMu.RLock()
67 stopped := e.stopped
68 e.stoppedMu.RUnlock()
69 if stopped {
70 return nil
71 }
72
73 if len(spans) == 0 {
74 return nil
75 }
76
77 stubs := tracetest.SpanStubsFromReadOnlySpans(spans)
78
79 e.encoderMu.Lock()
80 defer e.encoderMu.Unlock()
81 for i := range stubs {
82 stub := &stubs[i]
83 // Remove timestamps
84 if !e.timestamps {
85 stub.StartTime = zeroTime
86 stub.EndTime = zeroTime
87 for j := range stub.Events {
88 ev := &stub.Events[j]
89 ev.Time = zeroTime
90 }
91 }
92
93 // Encode span stubs, one by one
94 if e := e.encoder.Encode(stub); e != nil {
95 err = errors.Join(err, fmt.Errorf("failed to encode span %d: %w", i, e))
96 continue
97 }
98 success++
99 }
100 return err
101 }
102
103 // Shutdown is called to stop the exporter, it performs no action.
104 func (e *Exporter) Shutdown(context.Context) error {
105 e.stoppedMu.Lock()
106 e.stopped = true
107 e.stoppedMu.Unlock()
108
109 return nil
110 }
111
112 // MarshalLog is the marshaling function used by the logging system to represent this Exporter.
113 func (e *Exporter) MarshalLog() any {
114 return struct {
115 Type string
116 WithTimestamps bool
117 }{
118 Type: "stdout",
119 WithTimestamps: e.timestamps,
120 }
121 }