github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/log/syslog.go (about) 1 package log 2 3 import ( 4 "log/syslog" 5 6 "github.com/pkg/errors" 7 "go.uber.org/zap/zapcore" 8 ) 9 10 type syslogCore struct { 11 zapcore.LevelEnabler 12 encoder zapcore.Encoder 13 w *syslog.Writer 14 } 15 16 func NewSyslogCore(levelEnabler zapcore.LevelEnabler, encoder zapcore.Encoder, tag string) (*syslogCore, error) { 17 c := &syslogCore{ 18 LevelEnabler: levelEnabler, 19 encoder: encoder, 20 } 21 var err error 22 c.w, err = syslog.New(syslog.LOG_DAEMON, tag) 23 if err != nil { 24 return nil, err 25 } 26 27 return c, nil 28 } 29 30 func (s *syslogCore) clone() *syslogCore { 31 return &syslogCore{ 32 LevelEnabler: s.LevelEnabler, 33 encoder: s.encoder.Clone(), 34 w: s.w, 35 } 36 } 37 38 func (s *syslogCore) With(fields []zapcore.Field) zapcore.Core { 39 clone := s.clone() 40 for _, field := range fields { 41 field.AddTo(clone.encoder) 42 } 43 44 return clone 45 } 46 47 func (s *syslogCore) Check(entry zapcore.Entry, checkedEntry *zapcore.CheckedEntry) *zapcore.CheckedEntry { 48 if s.Enabled(entry.Level) { 49 return checkedEntry.AddCore(entry, s) 50 } 51 52 return checkedEntry 53 } 54 55 func (s *syslogCore) Write(entry zapcore.Entry, fields []zapcore.Field) error { 56 // Generate the message. 57 buffer, err := s.encoder.EncodeEntry(entry, fields) 58 if err != nil { 59 return errors.Wrap(err, "failed to encode log entry") 60 } 61 defer buffer.Free() 62 63 message := buffer.String() 64 65 // Write the message. 66 switch entry.Level { 67 case zapcore.DebugLevel: 68 return s.w.Debug(message) 69 70 case zapcore.InfoLevel: 71 return s.w.Info(message) 72 73 case zapcore.WarnLevel: 74 return s.w.Warning(message) 75 76 case zapcore.ErrorLevel: 77 return s.w.Err(message) 78 79 case zapcore.DPanicLevel: 80 return s.w.Crit(message) 81 82 case zapcore.PanicLevel: 83 return s.w.Crit(message) 84 85 case zapcore.FatalLevel: 86 return s.w.Crit(message) 87 88 default: 89 return errors.Errorf("unknown log level: %v", entry.Level) 90 } 91 } 92 93 func (s *syslogCore) Sync() error { 94 return nil 95 }