mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-22 23:12:15 +08:00
docs: 手动实现 simple log 日志库
日志文件分割
This commit is contained in:
parent
2e5e381d70
commit
f472470291
@ -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,
|
||||
}
|
||||
}
|
||||
|
@ -51,6 +51,7 @@ func TestLogToFile(t *testing.T) {
|
||||
log := NewLog(
|
||||
WithLogFile(logFilePath),
|
||||
WithLogFlag(FlagInfo|FlagDebug|FlagWarn),
|
||||
WithSplitSize(1*K),
|
||||
)
|
||||
|
||||
log.Debug("Debug 日志 测试")
|
||||
|
Loading…
Reference in New Issue
Block a user