-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathraw_marshaler.go
83 lines (71 loc) · 2.05 KB
/
raw_marshaler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package kafkaexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/kafkaexporter"
import (
"encoding/json"
"errors"
"github.com/IBM/sarama"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
)
var errUnsupported = errors.New("unsupported serialization")
type rawMarshaler struct{}
func newRawMarshaler() rawMarshaler {
return rawMarshaler{}
}
func (r rawMarshaler) Marshal(logs plog.Logs, topic string) ([]*sarama.ProducerMessage, error) {
var messages []*sarama.ProducerMessage
for i := 0; i < logs.ResourceLogs().Len(); i++ {
rl := logs.ResourceLogs().At(i)
for j := 0; j < rl.ScopeLogs().Len(); j++ {
sl := rl.ScopeLogs().At(j)
for k := 0; k < sl.LogRecords().Len(); k++ {
lr := sl.LogRecords().At(k)
b, err := r.logBodyAsBytes(lr.Body())
if err != nil {
return nil, err
}
if len(b) == 0 {
continue
}
messages = append(messages, &sarama.ProducerMessage{
Topic: topic,
Value: sarama.ByteEncoder(b),
})
}
}
}
return messages, nil
}
func (r rawMarshaler) logBodyAsBytes(value pcommon.Value) ([]byte, error) {
switch value.Type() {
case pcommon.ValueTypeStr:
return r.interfaceAsBytes(value.Str())
case pcommon.ValueTypeBytes:
return value.Bytes().AsRaw(), nil
case pcommon.ValueTypeBool:
return r.interfaceAsBytes(value.Bool())
case pcommon.ValueTypeDouble:
return r.interfaceAsBytes(value.Double())
case pcommon.ValueTypeInt:
return r.interfaceAsBytes(value.Int())
case pcommon.ValueTypeEmpty:
return []byte{}, nil
case pcommon.ValueTypeSlice:
return r.interfaceAsBytes(value.Slice().AsRaw())
case pcommon.ValueTypeMap:
return r.interfaceAsBytes(value.Map().AsRaw())
default:
return nil, errUnsupported
}
}
func (r rawMarshaler) interfaceAsBytes(value any) ([]byte, error) {
if value == nil {
return []byte{}, nil
}
res, err := json.Marshal(value)
return res, err
}
func (r rawMarshaler) Encoding() string {
return "raw"
}