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
d1fdc3eacb
commit
2e5e381d70
@ -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,
|
||||
}
|
||||
}
|
||||
|
@ -49,7 +49,7 @@ func TestLogToFile(t *testing.T) {
|
||||
|
||||
fmt.Printf("写入日志文件 %s\n", logFilePath)
|
||||
log := NewLog(
|
||||
WithWriter(f),
|
||||
WithLogFile(logFilePath),
|
||||
WithLogFlag(FlagInfo|FlagDebug|FlagWarn),
|
||||
)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user