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 }