diff --git a/simplelog/simplelog.go b/simplelog/simplelog.go index 8b1690e..8eb3d4b 100644 --- a/simplelog/simplelog.go +++ b/simplelog/simplelog.go @@ -8,6 +8,15 @@ import ( "time" ) +const ( + B uint64 = 1 << (10 * iota) + K + M + G + T + P +) + // 自定义日志 type LogLevel struct { @@ -39,6 +48,8 @@ var ( type Logger struct { fn string w io.Writer + index int + splitSize uint64 timeFormat string loggerFormat string flag LevelFlag @@ -55,6 +66,31 @@ func (l *Logger) PrintLog(level LogLevel, log string) { return } + for { + if len(l.fn) == 0 { + break + } else { + file := l.w.(*os.File) + info, _ := file.Stat() + currentSize := uint64(info.Size()) + if currentSize < l.splitSize { + break + } else { + _ = file.Close() + for { + file, err := os.OpenFile(fmt.Sprintf("%s.%d", l.fn, l.index), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + l.index++ + if err != nil { + continue + } else { + l.w = file + break + } + } + } + } + } + pc, _, _, ok := runtime.Caller(2) var f *runtime.Func if ok { @@ -103,6 +139,7 @@ type Option struct { LogFormat string LevelFlag LevelFlag LogFile string + SplitSize uint64 } type OptionFunc func(*Option) @@ -146,6 +183,12 @@ func WithLogFile(filePath string) OptionFunc { } } +func WithSplitSize(size uint64) OptionFunc { + return func(option *Option) { + option.SplitSize = size + } +} + // 默认参数 var defaultOption = &Option{ Writer: os.Stdout, @@ -153,6 +196,7 @@ var defaultOption = &Option{ LogFormat: "%-22s %s %v --- [%20s] : %s\n", LevelFlag: FlagInfo | FlagWarn | FlagError | FlagDebug, LogFile: "", + SplitSize: 0, } // NewOption 构造 Option 参数 @@ -174,5 +218,6 @@ func NewLog(opts ...OptionFunc) *Logger { loggerFormat: opt.LogFormat, flag: opt.LevelFlag, fn: opt.LogFile, + splitSize: opt.SplitSize, } } diff --git a/simplelog/simplelog_test.go b/simplelog/simplelog_test.go index d9fcac4..b15e664 100644 --- a/simplelog/simplelog_test.go +++ b/simplelog/simplelog_test.go @@ -51,6 +51,7 @@ func TestLogToFile(t *testing.T) { log := NewLog( WithLogFile(logFilePath), WithLogFlag(FlagInfo|FlagDebug|FlagWarn), + WithSplitSize(1*K), ) log.Debug("Debug 日志 测试")