From c4439e938b31620f3a70d0e7029a7bb9ae1b70dc Mon Sep 17 00:00:00 2001 From: Ge Song Date: Tue, 25 Apr 2023 16:50:29 +0800 Subject: [PATCH] =?UTF-8?q?logotel/WithDefaultSpan=20=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E5=BD=93=20span=20=E6=B2=A1=E6=9C=89=E5=9C=A8=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E6=97=B6=E5=88=9B=E5=BB=BA=E6=96=B0=20span;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- logotel/option.go | 11 ++++++++++- logotel/processor.go | 13 +++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/logotel/option.go b/logotel/option.go index bd762ef..33503b8 100644 --- a/logotel/option.go +++ b/logotel/option.go @@ -22,7 +22,8 @@ func newConfig(opts ...Option) *config { func defaultConfig() *config { return &config{ - hasPool: false, + hasPool: false, + defaultSpan: false, } } @@ -34,6 +35,13 @@ func WithBufferPool(pool logjson.BytesBufferPool) Option { }) } +// WithDefaultSpan 设置当 span 没有在记录时创建新 span +func WithDefaultSpan(defaultSpan bool) Option { + return optionFunc(func(cfg *config) { + cfg.defaultSpan = defaultSpan + }) +} + // Option 配置 Processor type Option interface { apply(cfg *config) @@ -42,6 +50,7 @@ type Option interface { type config struct { bytesBufferPool logjson.BytesBufferPool hasPool bool + defaultSpan bool } type optionFunc func(cfg *config) diff --git a/logotel/processor.go b/logotel/processor.go index 8f9f89c..3dec5ce 100644 --- a/logotel/processor.go +++ b/logotel/processor.go @@ -9,6 +9,7 @@ import ( "git.blauwelle.com/go/crate/log/logsdk" "git.blauwelle.com/go/crate/log/logsdk/logjson" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" @@ -19,7 +20,8 @@ import ( func New(opts ...Option) *Processor { cfg := newConfig(opts...) return &Processor{ - bufferPool: cfg.bytesBufferPool, + bufferPool: cfg.bytesBufferPool, + defaultSpan: cfg.defaultSpan, } } @@ -27,11 +29,18 @@ var _ logsdk.EntryProcessor = &Processor{} // Processor 用于把日志和 opentelemetry 对接 type Processor struct { - bufferPool logjson.BytesBufferPool + bufferPool logjson.BytesBufferPool + defaultSpan bool } func (processor *Processor) Process(ctx context.Context, entry logsdk.ReadonlyEntry) { span := trace.SpanFromContext(ctx) + if !span.IsRecording() { + if processor.defaultSpan { + ctx, span = otel.Tracer("git.blauwelle.com/go/crate/logotel").Start(ctx, "default") //nolint:ineffassign,staticcheck,wastedassign + defer span.End() + } + } if !span.IsRecording() { return }