From 66460386d86328a0d5ac16e14a3d397ed9379190 Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Fri, 17 May 2024 13:24:46 +0530 Subject: [PATCH] otelzap: Implement Enabled method (#5594) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #5191 --------- Co-authored-by: Robert PajÄ…k --- bridges/otelzap/core.go | 5 +++-- bridges/otelzap/core_test.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/bridges/otelzap/core.go b/bridges/otelzap/core.go index 6ea0bf0ad56..956f5d2657a 100644 --- a/bridges/otelzap/core.go +++ b/bridges/otelzap/core.go @@ -107,10 +107,11 @@ func NewCore(opts ...Option) *Core { } } -// TODO // LevelEnabler decides whether a given logging level is enabled when logging a message. func (o *Core) Enabled(level zapcore.Level) bool { - return true + r := log.Record{} + r.SetSeverity(convertLevel(level)) + return o.logger.Enabled(context.Background(), r) } // TODO diff --git a/bridges/otelzap/core_test.go b/bridges/otelzap/core_test.go index e4babb78a15..dc9cb18624c 100644 --- a/bridges/otelzap/core_test.go +++ b/bridges/otelzap/core_test.go @@ -4,6 +4,7 @@ package otelzap import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -17,8 +18,9 @@ import ( "go.opentelemetry.io/otel/sdk/instrumentation" ) +var testMessage = "log message" + func TestCore(t *testing.T) { - testMessage := "log message" rec := logtest.NewRecorder() zc := NewCore(WithLoggerProvider(rec)) logger := zap.New(zc) @@ -31,6 +33,31 @@ func TestCore(t *testing.T) { assert.Equal(t, log.SeverityInfo, got.Severity()) } +func TestCoreEnabled(t *testing.T) { + enabledFunc := func(c context.Context, r log.Record) bool { + return r.Severity() >= log.SeverityInfo + } + + r := logtest.NewRecorder(logtest.WithEnabledFunc(enabledFunc)) + logger := zap.New(NewCore(WithLoggerProvider(r))) + + logger.Debug(testMessage) + assert.Empty(t, r.Result()[1].Records) + + if ce := logger.Check(zap.DebugLevel, testMessage); ce != nil { + ce.Write() + } + assert.Empty(t, r.Result()[1].Records) + + if ce := logger.Check(zap.InfoLevel, testMessage); ce != nil { + ce.Write() + } + require.Len(t, r.Result()[1].Records, 1) + got := r.Result()[1].Records[0] + assert.Equal(t, testMessage, got.Body().AsString()) + assert.Equal(t, log.SeverityInfo, got.Severity()) +} + func TestNewCoreConfiguration(t *testing.T) { t.Run("Default", func(t *testing.T) { r := logtest.NewRecorder()