go.temporal.io/server@v1.23.0/common/log/slog_test.go (about) 1 // The MIT License 2 // 3 // Copyright (c) 2023 Temporal Technologies Inc. All rights reserved. 4 // 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 // 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 // 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 package log 24 25 import ( 26 "context" 27 "encoding/json" 28 "log/slog" 29 "testing" 30 31 "github.com/stretchr/testify/require" 32 "go.temporal.io/server/common/log/tag" 33 "go.temporal.io/server/common/quotas" 34 "go.uber.org/zap" 35 "go.uber.org/zap/zapcore" 36 ) 37 38 type writeBuffer struct { 39 buf []byte 40 } 41 42 var _ zapcore.WriteSyncer = (*writeBuffer)(nil) 43 44 // Sync implements zapcore.WriteSyncer. 45 func (*writeBuffer) Sync() error { 46 return nil 47 } 48 49 // Write implements zapcore.WriteSyncer. 50 func (b *writeBuffer) Write(p []byte) (n int, err error) { 51 b.buf = append(b.buf, p...) 52 return len(p), nil 53 } 54 55 func TestSlogFromLayeredLogger(t *testing.T) { 56 buffer := writeBuffer{nil} 57 core := zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), &buffer, zap.InfoLevel) 58 l := NewSlogLogger(NewThrottledLogger(With(NewZapLogger(zap.New(core)), tag.ClusterName("corn")), quotas.InfDuration.Hours)) 59 require.True(t, l.Enabled(context.Background(), slog.LevelInfo)) 60 require.False(t, l.Enabled(context.Background(), slog.LevelDebug)) 61 l.With("a", "b").WithGroup("hey").With("ho", "lets").WithGroup("go").With("c", 4).Info("wow", "gg", "wp") 62 var record map[string]any 63 err := json.Unmarshal(buffer.buf, &record) 64 require.NoError(t, err) 65 require.Equal(t, "b", record["a"]) 66 require.Equal(t, "lets", record["hey.ho"]) 67 require.Equal(t, float64(4), record["hey.go.c"]) // untyped json unmarshals numbers as floats 68 require.Equal(t, "wp", record["hey.go.gg"]) 69 require.Equal(t, "wow", record["msg"]) 70 require.Equal(t, "corn", record["cluster-name"]) 71 require.Equal(t, "slog_test.go:61", record["logging-call-at"]) 72 }