Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stdoutlog: Add exporter #5172

Merged
merged 24 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions exporters/stdout/stdoutlog/exporter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package stdoutlog // import "go.opentelemetry.io/otel/exporters/stdout/stdoutlog"

import (
"context"
"encoding/json"
"sync/atomic"
"time"

"go.opentelemetry.io/otel/sdk/log"
)

var zeroTime time.Time
XSAM marked this conversation as resolved.
Show resolved Hide resolved

var _ log.Exporter = &Exporter{}

// Exporter is an implementation of that writes spans to stdout.
XSAM marked this conversation as resolved.
Show resolved Hide resolved
type Exporter struct {
encoder *json.Encoder
timestamps bool

stopped atomic.Bool
}

// New creates an Exporter with the passed options.
pellared marked this conversation as resolved.
Show resolved Hide resolved
func New(options ...Option) (*Exporter, error) {
cfg := newConfig(options)

enc := json.NewEncoder(cfg.Writer)
if cfg.PrettyPrint {
enc.SetIndent("", "\t")
}

return &Exporter{
encoder: enc,
timestamps: cfg.Timestamps,
}, nil
}

// Export exports log records to writer.
// The writer is os.Stdout by default.
pellared marked this conversation as resolved.
Show resolved Hide resolved
func (e *Exporter) Export(ctx context.Context, records []log.Record) error {
if e.stopped.Load() {
return nil
}

for i, record := range records {
// Honor context cancellation.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
XSAM marked this conversation as resolved.
Show resolved Hide resolved

// Remove timestamps.
if !e.timestamps {
// Clone before make changes.
record = records[i].Clone()

record.SetTimestamp(zeroTime)
record.SetObservedTimestamp(zeroTime)
}
XSAM marked this conversation as resolved.
Show resolved Hide resolved

// Encode record, one by one.
recordJSON := newRecordJSON(record)
if err := e.encoder.Encode(recordJSON); err != nil {
XSAM marked this conversation as resolved.
Show resolved Hide resolved
return err

Check warning on line 69 in exporters/stdout/stdoutlog/exporter.go

View check run for this annotation

Codecov / codecov/patch

exporters/stdout/stdoutlog/exporter.go#L69

Added line #L69 was not covered by tests
}
}
return nil
}

// Shutdown stops the exporter.
pellared marked this conversation as resolved.
Show resolved Hide resolved
func (e *Exporter) Shutdown(ctx context.Context) error {
XSAM marked this conversation as resolved.
Show resolved Hide resolved
e.stopped.Store(true)
// Free the encoder resources.
e.encoder = nil

return nil
}

// ForceFlush performs no action.
func (e *Exporter) ForceFlush(ctx context.Context) error {
return nil
}
228 changes: 228 additions & 0 deletions exporters/stdout/stdoutlog/exporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package stdoutlog_test // import "go.opentelemetry.io/otel/exporters/stdout/stdoutout"

import (
"bytes"
"context"
"encoding/json"
"testing"
"time"

"github.com/stretchr/testify/assert"

"go.opentelemetry.io/otel/exporters/stdout/stdoutlog"
"go.opentelemetry.io/otel/log"
sdklog "go.opentelemetry.io/otel/sdk/log"
"go.opentelemetry.io/otel/trace"
)

func TestExporter(t *testing.T) {
var buf bytes.Buffer

exporter, err := stdoutlog.New(stdoutlog.WithWriter(&buf))
assert.NoError(t, err)
assert.NotNil(t, exporter)

now := time.Now()
record := getRecord(now)

// Export a record
err = exporter.Export(context.Background(), []sdklog.Record{record})
pellared marked this conversation as resolved.
Show resolved Hide resolved
assert.NoError(t, err)

// Check the writer
assert.Equal(t, expectedJSON(now, false), buf.String())

// Flush the exporter
err = exporter.ForceFlush(context.Background())
assert.NoError(t, err)

// Shutdown the exporter
err = exporter.Shutdown(context.Background())
assert.NoError(t, err)

// Export a record after shutdown, this should not be written
err = exporter.Export(context.Background(), []sdklog.Record{record})
assert.NoError(t, err)

// Check the writer
assert.Equal(t, expectedJSON(now, false), buf.String())
}

func TestExporterExport(t *testing.T) {
now := time.Now()

record := getRecord(now)
records := []sdklog.Record{record, record}

// Get canceled context
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
XSAM marked this conversation as resolved.
Show resolved Hide resolved

testCases := []struct {
name string
options []stdoutlog.Option
ctx context.Context
records []sdklog.Record
expectedResult string
expectedError error
XSAM marked this conversation as resolved.
Show resolved Hide resolved
}{
{
name: "default",
options: []stdoutlog.Option{},
ctx: context.Background(),
records: records,
expectedResult: expectedJSONs(now, false),
},
{
name: "NoRecords",
options: []stdoutlog.Option{},
ctx: context.Background(),
records: nil,
expectedResult: "",
},
{
name: "WithPrettyPrint",
options: []stdoutlog.Option{stdoutlog.WithPrettyPrint()},
ctx: context.Background(),
records: records,
expectedResult: expectedJSONs(now, true),
},
{
name: "WithoutTimestamps",
options: []stdoutlog.Option{stdoutlog.WithoutTimestamps()},
ctx: context.Background(),
records: records,
expectedResult: expectedJSONs(time.Time{}, false),
},
{
name: "WithoutTimestamps and WithPrettyPrint",
options: []stdoutlog.Option{stdoutlog.WithoutTimestamps(), stdoutlog.WithPrettyPrint()},
ctx: context.Background(),
records: records,
expectedResult: expectedJSONs(time.Time{}, true),
},
{
name: "WithCanceledContext",
ctx: canceledCtx,
records: records,
expectedResult: "",
expectedError: context.Canceled,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Write to buffer for testing
var buf bytes.Buffer

exporter, err := stdoutlog.New(append(tc.options, stdoutlog.WithWriter(&buf))...)
assert.NoError(t, err)

err = exporter.Export(tc.ctx, tc.records)
assert.Equal(t, tc.expectedError, err)
assert.Equal(t, tc.expectedResult, buf.String())
})
}
}

func expectedJSONs(now time.Time, prettyPrint bool) string {
result := expectedJSON(now, prettyPrint)
return result + result
}

// revive:disable-next-line:flag-parameter
func expectedJSON(now time.Time, prettyPrint bool) string {
serializedNow, _ := json.Marshal(now)
if prettyPrint {
XSAM marked this conversation as resolved.
Show resolved Hide resolved
return `{
"Timestamp": ` + string(serializedNow) + `,
"ObservedTimestamp": ` + string(serializedNow) + `,
"Severity": 9,
"SeverityText": "INFO",
"Body": {},
"Attributes": [
{
"Key": "key",
"Value": {}
},
{
"Key": "key2",
"Value": {}
},
{
"Key": "key3",
"Value": {}
},
{
"Key": "key4",
"Value": {}
},
{
"Key": "key5",
"Value": {}
},
{
"Key": "bool",
"Value": {}
}
],
"TraceID": "0102030405060708090a0b0c0d0e0f10",
"SpanID": "0102030405060708",
"TraceFlags": "01",
"Resource": {},
"Scope": {
"Name": "",
"Version": "",
"SchemaURL": ""
},
"AttributeValueLengthLimit": 0,
"AttributeCountLimit": 0
}
`
}
return "{\"Timestamp\":" + string(serializedNow) + ",\"ObservedTimestamp\":" + string(serializedNow) + ",\"Severity\":9,\"SeverityText\":\"INFO\",\"Body\":{},\"Attributes\":[{\"Key\":\"key\",\"Value\":{}},{\"Key\":\"key2\",\"Value\":{}},{\"Key\":\"key3\",\"Value\":{}},{\"Key\":\"key4\",\"Value\":{}},{\"Key\":\"key5\",\"Value\":{}},{\"Key\":\"bool\",\"Value\":{}}],\"TraceID\":\"0102030405060708090a0b0c0d0e0f10\",\"SpanID\":\"0102030405060708\",\"TraceFlags\":\"01\",\"Resource\":{},\"Scope\":{\"Name\":\"\",\"Version\":\"\",\"SchemaURL\":\"\"},\"AttributeValueLengthLimit\":0,\"AttributeCountLimit\":0}\n"
}

func TestExporterShutdown(t *testing.T) {
exporter, err := stdoutlog.New()
assert.NoError(t, err)

assert.NoError(t, exporter.Shutdown(context.Background()))
}

func TestExporterForceFlush(t *testing.T) {
exporter, err := stdoutlog.New()
assert.NoError(t, err)

assert.NoError(t, exporter.ForceFlush(context.Background()))
}

func getRecord(now time.Time) sdklog.Record {
traceID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10")
spanID, _ := trace.SpanIDFromHex("0102030405060708")

// Setup records
record := sdklog.Record{}
record.SetTimestamp(now)
record.SetObservedTimestamp(now)
record.SetSeverity(log.SeverityInfo1)
record.SetSeverityText("INFO")
record.SetBody(log.StringValue("test"))
record.SetAttributes([]log.KeyValue{
// More than 5 attributes to test back slice
log.String("key", "value"),
log.String("key2", "value"),
log.String("key3", "value"),
log.String("key4", "value"),
log.String("key5", "value"),
log.Bool("bool", true),
}...)
record.SetTraceID(traceID)
record.SetSpanID(spanID)
record.SetTraceFlags(trace.FlagsSampled)

return record
}
25 changes: 24 additions & 1 deletion exporters/stdout/stdoutlog/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,33 @@ module go.opentelemetry.io/otel/exporters/stdout/stdoutlog

go 1.21

require github.com/stretchr/testify v1.9.0
require (
github.com/stretchr/testify v1.9.0
go.opentelemetry.io/otel/log v0.1.0-alpha
go.opentelemetry.io/otel/sdk v1.25.0
go.opentelemetry.io/otel/sdk/log v0.0.0
go.opentelemetry.io/otel/trace v1.25.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.opentelemetry.io/otel v1.25.0 // indirect
go.opentelemetry.io/otel/metric v1.25.0 // indirect
golang.org/x/sys v0.19.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace go.opentelemetry.io/otel/sdk/log => ../../../sdk/log

replace go.opentelemetry.io/otel/log => ../../../log

replace go.opentelemetry.io/otel => ../../..

replace go.opentelemetry.io/otel/trace => ../../../trace

replace go.opentelemetry.io/otel/sdk => ../../../sdk

replace go.opentelemetry.io/otel/metric => ../../../metric
9 changes: 9 additions & 0 deletions exporters/stdout/stdoutlog/go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
Loading