-
Notifications
You must be signed in to change notification settings - Fork 591
/
Copy pathcore.go
209 lines (179 loc) · 5.06 KB
/
core.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Package otelzap provides a bridge between the [go.uber.org/zap] and
// OpenTelemetry logging.
package otelzap // import "go.opentelemetry.io/contrib/bridges/otelzap"
import (
"context"
"slices"
"go.uber.org/zap/zapcore"
"go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/log/global"
)
type config struct {
provider log.LoggerProvider
version string
schemaURL string
}
func newConfig(options []Option) config {
var c config
for _, opt := range options {
c = opt.apply(c)
}
if c.provider == nil {
c.provider = global.GetLoggerProvider()
}
return c
}
func (c config) logger(name string) log.Logger {
var opts []log.LoggerOption
if c.version != "" {
opts = append(opts, log.WithInstrumentationVersion(c.version))
}
if c.schemaURL != "" {
opts = append(opts, log.WithSchemaURL(c.schemaURL))
}
return c.provider.Logger(name, opts...)
}
// Option configures a [Core].
type Option interface {
apply(config) config
}
type optFunc func(config) config
func (f optFunc) apply(c config) config { return f(c) }
// WithVersion returns an [Option] that configures the version of the
// [log.Logger] used by a [Core]. The version should be the version of the
// package that is being logged.
func WithVersion(version string) Option {
return optFunc(func(c config) config {
c.version = version
return c
})
}
// WithSchemaURL returns an [Option] that configures the semantic convention
// schema URL of the [log.Logger] used by a [Core]. The schemaURL should be
// the schema URL for the semantic conventions used in log records.
func WithSchemaURL(schemaURL string) Option {
return optFunc(func(c config) config {
c.schemaURL = schemaURL
return c
})
}
// WithLoggerProvider returns an [Option] that configures [log.LoggerProvider]
// used by a [Core] to create its [log.Logger].
//
// By default if this Option is not provided, the Handler will use the global
// LoggerProvider.
func WithLoggerProvider(provider log.LoggerProvider) Option {
return optFunc(func(c config) config {
c.provider = provider
return c
})
}
// Core is a [zapcore.Core] that sends logging records to OpenTelemetry.
type Core struct {
logger log.Logger
attr []log.KeyValue
ctx context.Context
}
// Compile-time check *Core implements zapcore.Core.
var _ zapcore.Core = (*Core)(nil)
// NewCore creates a new [zapcore.Core] that can be used with [go.uber.org/zap.New].
func NewCore(name string, opts ...Option) *Core {
cfg := newConfig(opts)
return &Core{
logger: cfg.logger(name),
ctx: context.Background(),
}
}
// Enabled decides whether a given logging level is enabled when logging a message.
func (o *Core) Enabled(level zapcore.Level) bool {
r := log.Record{}
r.SetSeverity(convertLevel(level))
return o.logger.Enabled(context.Background(), r)
}
// With adds structured context to the Core.
func (o *Core) With(fields []zapcore.Field) zapcore.Core {
cloned := o.clone()
if len(fields) > 0 {
ctx, attrbuf := convertField(fields)
if ctx != nil {
cloned.ctx = ctx
}
cloned.attr = append(cloned.attr, attrbuf...)
}
return cloned
}
func (o *Core) clone() *Core {
return &Core{
logger: o.logger,
attr: slices.Clone(o.attr),
ctx: o.ctx,
}
}
// TODO
// Sync flushes buffered logs (if any).
func (o *Core) Sync() error {
return nil
}
// Check determines whether the supplied Entry should be logged using core.Enabled method.
// If the entry should be logged, the Core adds itself to the CheckedEntry and returns the result.
func (o *Core) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if o.Enabled(ent.Level) {
return ce.AddCore(ent, o)
}
return ce
}
// Write method encodes zap fields to OTel logs and emits them.
func (o *Core) Write(ent zapcore.Entry, fields []zapcore.Field) error {
r := log.Record{}
r.SetTimestamp(ent.Time)
r.SetBody(log.StringValue(ent.Message))
r.SetSeverity(convertLevel(ent.Level))
r.SetSeverityText(ent.Level.String())
// TODO: Handle ent.LoggerName.
r.AddAttributes(o.attr...)
if len(fields) > 0 {
ctx, attrbuf := convertField(fields)
if ctx != nil {
o.ctx = ctx
}
r.AddAttributes(attrbuf...)
}
o.logger.Emit(o.ctx, r)
return nil
}
func convertField(fields []zapcore.Field) (context.Context, []log.KeyValue) {
// TODO: Use objectEncoder from a pool instead of newObjectEncoder.
var ctx context.Context
enc := newObjectEncoder(len(fields))
for _, field := range fields {
if ctxFld, ok := field.Interface.(context.Context); ok {
ctx = ctxFld
continue
}
field.AddTo(enc)
}
enc.calculate(enc.root)
return ctx, enc.root.attrs
}
func convertLevel(level zapcore.Level) log.Severity {
switch level {
case zapcore.DebugLevel:
return log.SeverityDebug
case zapcore.InfoLevel:
return log.SeverityInfo
case zapcore.WarnLevel:
return log.SeverityWarn
case zapcore.ErrorLevel:
return log.SeverityError
case zapcore.DPanicLevel:
return log.SeverityFatal1
case zapcore.PanicLevel:
return log.SeverityFatal2
case zapcore.FatalLevel:
return log.SeverityFatal3
default:
return log.SeverityUndefined
}
}