| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// Package logtest is a testing helper package. |
| 5 |
package logtest // import "go.opentelemetry.io/otel/sdk/log/logtest" |
| 6 |
|
| 7 |
import ( |
| 8 |
"reflect" |
| 9 |
"time" |
| 10 |
"unsafe" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel/log" |
| 13 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 14 |
sdklog "go.opentelemetry.io/otel/sdk/log" |
| 15 |
"go.opentelemetry.io/otel/sdk/resource" |
| 16 |
"go.opentelemetry.io/otel/trace" |
| 17 |
) |
| 18 |
|
| 19 |
// RecordFactory is used to facilitate unit testing implementations of |
| 20 |
// [go.opentelemetry.io/otel/sdk/log.Exporter] |
| 21 |
// and [go.opentelemetry.io/otel/sdk/log.Processor]. |
| 22 |
// |
| 23 |
// Do not use RecordFactory to create records in production code. |
| 24 |
type RecordFactory struct { |
| 25 |
EventName string |
| 26 |
Timestamp time.Time |
| 27 |
ObservedTimestamp time.Time |
| 28 |
Severity log.Severity |
| 29 |
SeverityText string |
| 30 |
Body log.Value |
| 31 |
Attributes []log.KeyValue |
| 32 |
TraceID trace.TraceID |
| 33 |
SpanID trace.SpanID |
| 34 |
TraceFlags trace.TraceFlags |
| 35 |
|
| 36 |
Resource *resource.Resource |
| 37 |
InstrumentationScope *instrumentation.Scope |
| 38 |
|
| 39 |
DroppedAttributes int |
| 40 |
AttributeValueLengthLimit int |
| 41 |
AttributeCountLimit int |
| 42 |
} |
| 43 |
|
| 44 |
// NewRecord returns a [sdklog.Record] configured from the values of f. |
| 45 |
func (f RecordFactory) NewRecord() sdklog.Record { |
| 46 |
// r needs to be addressable for set() below. |
| 47 |
r := new(sdklog.Record) |
| 48 |
|
| 49 |
// Set to unlimited so attributes are set exactly. |
| 50 |
set(r, "attributeCountLimit", -1) |
| 51 |
set(r, "attributeValueLengthLimit", -1) |
| 52 |
|
| 53 |
r.SetEventName(f.EventName) |
| 54 |
r.SetTimestamp(f.Timestamp) |
| 55 |
r.SetObservedTimestamp(f.ObservedTimestamp) |
| 56 |
r.SetSeverity(f.Severity) |
| 57 |
r.SetSeverityText(f.SeverityText) |
| 58 |
r.SetBody(f.Body) |
| 59 |
r.SetAttributes(f.Attributes...) |
| 60 |
r.SetTraceID(f.TraceID) |
| 61 |
r.SetSpanID(f.SpanID) |
| 62 |
r.SetTraceFlags(f.TraceFlags) |
| 63 |
|
| 64 |
set(r, "resource", f.Resource) |
| 65 |
set(r, "scope", f.InstrumentationScope) |
| 66 |
set(r, "dropped", f.DroppedAttributes) |
| 67 |
set(r, "attributeCountLimit", f.AttributeCountLimit) |
| 68 |
set(r, "attributeValueLengthLimit", f.AttributeValueLengthLimit) |
| 69 |
|
| 70 |
return *r |
| 71 |
} |
| 72 |
|
| 73 |
func set(r *sdklog.Record, name string, value any) { |
| 74 |
rVal := reflect.ValueOf(r).Elem() |
| 75 |
rf := rVal.FieldByName(name) |
| 76 |
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())). |
| 77 |
Elem() |
| 78 |
// nolint: gosec // conversion of uintptr -> unsafe.Pointer. |
| 79 |
rf.Set(reflect.ValueOf(value)) |
| 80 |
} |