github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/logger/zaputil/zaputil.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package zaputil 16 17 import ( 18 "go.uber.org/zap" 19 "go.uber.org/zap/zapcore" 20 ) 21 22 func encoderWithValues(enc zapcore.Encoder, kvs ...any) zapcore.Encoder { 23 clone := enc.Clone() 24 for i := 1; i < len(kvs); i += 2 { 25 if key, ok := kvs[i-1].(string); ok { 26 zap.Any(key, kvs[i]).AddTo(clone) 27 } 28 } 29 return clone 30 } 31 32 type Encoder[T any] interface { 33 WithValues(kvs ...any) T 34 Core(console, json *WriteEnabler) zapcore.Core 35 } 36 37 type DevelopmentEncoder struct { 38 console zapcore.Encoder 39 json zapcore.Encoder 40 } 41 42 func NewDevelopmentEncoder() DevelopmentEncoder { 43 return DevelopmentEncoder{ 44 console: zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), 45 json: zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), 46 } 47 } 48 49 func (e DevelopmentEncoder) WithValues(kvs ...any) DevelopmentEncoder { 50 e.console = encoderWithValues(e.console, kvs...) 51 e.json = encoderWithValues(e.json, kvs...) 52 return e 53 } 54 55 func (e DevelopmentEncoder) Core(console, json *WriteEnabler) zapcore.Core { 56 return zapcore.NewTee(NewEncoderCore(e.console, console), NewEncoderCore(e.json, json)) 57 } 58 59 type ProductionEncoder struct { 60 json zapcore.Encoder 61 } 62 63 func NewProductionEncoder() ProductionEncoder { 64 return ProductionEncoder{ 65 json: zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), 66 } 67 } 68 69 func (e ProductionEncoder) WithValues(kvs ...any) ProductionEncoder { 70 e.json = encoderWithValues(e.json, kvs...) 71 return e 72 } 73 74 func (e ProductionEncoder) Core(console, json *WriteEnabler) zapcore.Core { 75 return NewEncoderCore(e.json, console, json) 76 }