github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/logger/zaputil/encoder.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/multierr" 19 "go.uber.org/zap/zapcore" 20 ) 21 22 type WriteEnabler struct { 23 zapcore.WriteSyncer 24 zapcore.LevelEnabler 25 } 26 27 func NewWriteEnabler(ws zapcore.WriteSyncer, enab zapcore.LevelEnabler) *WriteEnabler { 28 return &WriteEnabler{ws, enab} 29 } 30 31 type discardWriteSyncer struct{} 32 33 func (discardWriteSyncer) Write(p []byte) (int, error) { return len(p), nil } 34 func (discardWriteSyncer) Sync() error { return nil } 35 36 func NewDiscardWriteEnabler() *WriteEnabler { 37 return NewWriteEnabler(discardWriteSyncer{}, zapcore.FatalLevel) 38 } 39 40 func NewEncoderCore(enc zapcore.Encoder, out ...*WriteEnabler) zapcore.Core { 41 return &encoderCore{ 42 enc: enc, 43 out: out, 44 } 45 } 46 47 type encoderCore struct { 48 enc zapcore.Encoder 49 out []*WriteEnabler 50 } 51 52 func (c encoderCore) Level() zapcore.Level { 53 minLvl := zapcore.FatalLevel 54 for _, out := range c.out { 55 if lvl := zapcore.LevelOf(out); lvl < minLvl { 56 minLvl = lvl 57 } 58 } 59 return minLvl 60 } 61 62 func (c encoderCore) Enabled(lvl zapcore.Level) bool { 63 for _, out := range c.out { 64 if out.Enabled(lvl) { 65 return true 66 } 67 } 68 return false 69 } 70 71 func (c *encoderCore) With(fields []zapcore.Field) zapcore.Core { 72 dup := *c 73 dup.enc = dup.enc.Clone() 74 for _, f := range fields { 75 f.AddTo(dup.enc) 76 } 77 return &dup 78 } 79 80 func (c *encoderCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry { 81 if c.Enabled(ent.Level) { 82 return ce.AddCore(ent, c) 83 } 84 return ce 85 } 86 87 func (c *encoderCore) Write(ent zapcore.Entry, fields []zapcore.Field) error { 88 buf, err := c.enc.EncodeEntry(ent, fields) 89 if err != nil { 90 return err 91 } 92 for _, out := range c.out { 93 if out.Enabled(ent.Level) { 94 _, werr := out.Write(buf.Bytes()) 95 err = multierr.Append(err, werr) 96 } 97 } 98 buf.Free() 99 if err != nil { 100 return err 101 } 102 if ent.Level > zapcore.ErrorLevel { 103 _ = c.Sync() 104 } 105 return nil 106 } 107 108 func (c *encoderCore) Sync() error { 109 var err error 110 for _, out := range c.out { 111 err = multierr.Append(err, out.Sync()) 112 } 113 return err 114 }