github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/log/log_test.go (about) 1 package log_test 2 3 import ( 4 "os" 5 "testing" 6 7 "github.com/ronaksoft/rony/di" 8 "github.com/ronaksoft/rony/log" 9 . "github.com/smartystreets/goconvey/convey" 10 "go.uber.org/zap" 11 ) 12 13 func TestLog(t *testing.T) { 14 Convey("Log", t, func(c C) { 15 Convey("Different styles", func(c C) { 16 l := log.New() 17 l.SetLevel(log.DebugLevel) 18 l.Info("INFO", zap.Int("Index", 1)) 19 l.Sugared().Info("INFO", 1) 20 l.Sugared().Infof("INFO %d", 1) 21 ll := l.With("CHILD") 22 ll.SetLevel(log.DebugLevel) 23 ll.Info("INFO", zap.Int("Index", 1)) 24 ll.Sugared().Info("INFO", 1) 25 ll.Sugared().Infof("INFO %d", 1) 26 }) 27 Convey("Dependency Injection", func(c C) { 28 log.ProvideDI() 29 x := NewDI() 30 x.Info("DI Hooorraa") 31 32 log.ProvideDI() 33 x2 := NewDI() 34 x2.Info("DI Hooorraa2") 35 }) 36 Convey("Logger with SysLog", func(c C) { 37 l := log.New(log.WithSyslog("rony-logger")) 38 l.SetLevel(log.DebugLevel) 39 l.Info("INFO", zap.Int("Index", 1)) 40 l.Sugared().Info("INFO", 1) 41 l.Sugared().Infof("INFO %d", 1) 42 ll := l.With("CHILD") 43 ll.SetLevel(log.DebugLevel) 44 ll.Info("INFO", zap.Int("Index", 1)) 45 ll.Sugared().Info("INFO", 1) 46 ll.Sugared().Infof("INFO %d", 1) 47 }) 48 }) 49 } 50 51 func TestLogWithWriter(t *testing.T) { 52 Convey("Log With Added Writer", t, func(c C) { 53 Convey("File Writer", func(c C) { 54 _ = os.MkdirAll("./_hdd", os.ModePerm) 55 l := log.New() 56 l.Warn("Log1") 57 l.Info("Log2") 58 f, err := os.OpenFile( 59 "./_hdd/testlog.txt", 60 os.O_RDWR|os.O_CREATE|os.O_APPEND, 61 0666, 62 ) 63 c.So(err, ShouldBeNil) 64 l2 := l.WithCore(log.EncoderBuilder().ConsoleEncoder(), f) 65 l2.Warn("File Log1") 66 l2.Info("File Log2") 67 err = f.Close() 68 c.So(err, ShouldBeNil) 69 }) 70 }) 71 } 72 73 type DI struct { 74 l log.Logger 75 } 76 77 func NewDI() *DI { 78 d := &DI{} 79 di.MustInvoke(func(l log.Logger) { 80 d.l = l 81 }) 82 83 return d 84 } 85 86 func (di DI) Info(msg string, fields ...log.Field) { 87 di.l.Info(msg, fields...) 88 }