diff --git a/simplelog/simplelog.go b/simplelog/simplelog.go index 111fe9d..8b1690e 100644 --- a/simplelog/simplelog.go +++ b/simplelog/simplelog.go @@ -37,6 +37,7 @@ var ( // Logger 日志类 type Logger struct { + fn string w io.Writer timeFormat string loggerFormat string @@ -101,13 +102,16 @@ type Option struct { TimeFormat string LogFormat string LevelFlag LevelFlag + LogFile string } type OptionFunc func(*Option) func WithWriter(writer io.Writer) OptionFunc { return func(option *Option) { - option.Writer = writer + if len(option.LogFile) == 0 { + option.Writer = writer + } } } @@ -129,12 +133,26 @@ func WithLogFlag(flag LevelFlag) OptionFunc { } } +func WithLogFile(filePath string) OptionFunc { + return func(option *Option) { + if len(filePath) > 0 { + option.LogFile = filePath + file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + panic(err) + } + option.Writer = file + } + } +} + // 默认参数 var defaultOption = &Option{ Writer: os.Stdout, TimeFormat: "2006-01-02 15:04:05.99", LogFormat: "%-22s %s %v --- [%20s] : %s\n", LevelFlag: FlagInfo | FlagWarn | FlagError | FlagDebug, + LogFile: "", } // NewOption 构造 Option 参数 @@ -155,5 +173,6 @@ func NewLog(opts ...OptionFunc) *Logger { timeFormat: opt.TimeFormat, loggerFormat: opt.LogFormat, flag: opt.LevelFlag, + fn: opt.LogFile, } } diff --git a/simplelog/simplelog_test.go b/simplelog/simplelog_test.go index d253342..d9fcac4 100644 --- a/simplelog/simplelog_test.go +++ b/simplelog/simplelog_test.go @@ -49,7 +49,7 @@ func TestLogToFile(t *testing.T) { fmt.Printf("写入日志文件 %s\n", logFilePath) log := NewLog( - WithWriter(f), + WithLogFile(logFilePath), WithLogFlag(FlagInfo|FlagDebug|FlagWarn), )