From f472470291d58a0ffbaa94de801ea6cf3de4b55b Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Wed, 6 Oct 2021 21:36:23 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E6=89=8B=E5=8A=A8=E5=AE=9E=E7=8E=B0=20?= =?UTF-8?q?simple=20log=20=E6=97=A5=E5=BF=97=E5=BA=93=20=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=88=86=E5=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- simplelog/simplelog.go | 45 +++++++++++++++++++++++++++++++++++++ simplelog/simplelog_test.go | 1 + 2 files changed, 46 insertions(+) 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 日志 测试")