| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package stdoutlog // import "go.opentelemetry.io/otel/exporters/stdout/stdoutlog" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"encoding/json" |
| 9 |
"sync/atomic" |
| 10 |
|
| 11 |
"go.opentelemetry.io/otel/sdk/log" |
| 12 |
) |
| 13 |
|
| 14 |
var _ log.Exporter = &Exporter{} |
| 15 |
|
| 16 |
// Exporter writes JSON-encoded log records to an [io.Writer] ([os.Stdout] by default). |
| 17 |
// Exporter must be created with [New]. |
| 18 |
type Exporter struct { |
| 19 |
encoder atomic.Pointer[json.Encoder] |
| 20 |
timestamps bool |
| 21 |
} |
| 22 |
|
| 23 |
// New creates an [Exporter]. |
| 24 |
func New(options ...Option) (*Exporter, error) { |
| 25 |
cfg := newConfig(options) |
| 26 |
|
| 27 |
enc := json.NewEncoder(cfg.Writer) |
| 28 |
if cfg.PrettyPrint { |
| 29 |
enc.SetIndent("", "\t") |
| 30 |
} |
| 31 |
|
| 32 |
e := Exporter{ |
| 33 |
timestamps: cfg.Timestamps, |
| 34 |
} |
| 35 |
e.encoder.Store(enc) |
| 36 |
|
| 37 |
return &e, nil |
| 38 |
} |
| 39 |
|
| 40 |
// Export exports log records to writer. |
| 41 |
func (e *Exporter) Export(ctx context.Context, records []log.Record) error { |
| 42 |
enc := e.encoder.Load() |
| 43 |
if enc == nil { |
| 44 |
return nil |
| 45 |
} |
| 46 |
|
| 47 |
for _, record := range records { |
| 48 |
// Honor context cancellation. |
| 49 |
if err := ctx.Err(); err != nil { |
| 50 |
return err |
| 51 |
} |
| 52 |
|
| 53 |
// Encode record, one by one. |
| 54 |
recordJSON := e.newRecordJSON(record) |
| 55 |
if err := enc.Encode(recordJSON); err != nil { |
| 56 |
return err |
| 57 |
} |
| 58 |
} |
| 59 |
return nil |
| 60 |
} |
| 61 |
|
| 62 |
// Shutdown shuts down the Exporter. |
| 63 |
// Calls to Export will perform no operation after this is called. |
| 64 |
func (e *Exporter) Shutdown(context.Context) error { |
| 65 |
e.encoder.Store(nil) |
| 66 |
return nil |
| 67 |
} |
| 68 |
|
| 69 |
// ForceFlush performs no action. |
| 70 |
func (*Exporter) ForceFlush(context.Context) error { |
| 71 |
return nil |
| 72 |
} |