github.com/songzhibin97/gkit@v1.2.13/watching/log.go (about) 1 package watching 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "sync/atomic" 8 "time" 9 "unsafe" 10 ) 11 12 // log write content to log file. 13 func (w *Watching) logf(pattern string, args ...interface{}) { 14 if w.config.LogLevel >= LogLevelInfo { 15 timestamp := "[" + time.Now().Format("2006-01-02 15:04:05.000") + "]" 16 w.writeString(fmt.Sprintf(timestamp+pattern+"\n", args...)) 17 } 18 } 19 20 // log write content to log file. 21 func (w *Watching) debugf(pattern string, args ...interface{}) { 22 if w.config.LogLevel >= LogLevelDebug { 23 w.writeString(fmt.Sprintf(pattern+"\n", args...)) 24 } 25 } 26 27 func (w *Watching) writeString(content string) { 28 if _, err := w.config.Logger.WriteString(content); err != nil { 29 fmt.Println(err) // where to write this log? 30 } 31 32 if !w.config.logConfigs.RotateEnable { 33 return 34 } 35 36 state, err := w.config.Logger.Stat() 37 if err != nil { 38 w.config.logConfigs.RotateEnable = false 39 //nolint 40 fmt.Println("get logger stat:", err, "from now on, it will be disabled split log") 41 42 return 43 } 44 45 if state.Size() > w.config.logConfigs.SplitLoggerSize && atomic.CompareAndSwapInt32(&w.changeLog, 0, 1) { 46 defer atomic.StoreInt32(&w.changeLog, 0) 47 48 var ( 49 newLogger *os.File 50 err error 51 dumpPath = w.config.DumpPath 52 suffix = time.Now().Format("20060102150405") 53 srcPath = filepath.Clean(filepath.Join(dumpPath, defaultLoggerName)) 54 dstPath = srcPath + "_" + suffix + ".back" 55 ) 56 57 err = os.Rename(srcPath, dstPath) 58 59 if err != nil { 60 w.config.logConfigs.RotateEnable = false 61 //nolint 62 fmt.Println("rename err:", err, "from now on, it will be disabled split log") 63 64 return 65 } 66 67 newLogger, err = os.OpenFile(filepath.Clean(srcPath), defaultLoggerFlags, defaultLoggerPerm) 68 69 if err != nil { 70 w.config.logConfigs.RotateEnable = false 71 //nolint 72 fmt.Println("open new file err:", err, "from now on, it will be disabled split log") 73 74 return 75 } 76 77 old := w.config.Logger 78 if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&w.config.Logger)), unsafe.Pointer(w.config.Logger), unsafe.Pointer(newLogger)) { 79 _ = old.Close() 80 } 81 } 82 }