Skip to content

Commit

Permalink
Merge pull request #1 from wenweihu86/master
Browse files Browse the repository at this point in the history
修改level log,支持传入可变参数,类似于fmt.Printf
  • Loading branch information
cyy0523xc authored Dec 16, 2017
2 parents a5c968f + 15338c0 commit 5ed5755
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
25 changes: 14 additions & 11 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package asyncLog

import (
"math/rand"
"fmt"
)

// 日志优先级
Expand Down Expand Up @@ -41,35 +42,37 @@ func (lf *LogFile) SetLevel(logLevel Priority) {
lf.level = logLevel
}

func (lf *LogFile) Debug(msg string) error {
return lf.writeLevelMsg(msg, LevelDebug)
func (lf *LogFile) Debug(format string, a ...interface{}) error {
return lf.writeLevelMsg(LevelDebug, format, a...)
}

func (lf *LogFile) Info(msg string) error {
return lf.writeLevelMsg(msg, LevelInfo)
func (lf *LogFile) Info(format string, a ...interface{}) error {
return lf.writeLevelMsg(LevelInfo, format, a...)
}

func (lf *LogFile) Warn(msg string) error {
return lf.writeLevelMsg(msg, LevelWarn)
func (lf *LogFile) Warn(format string, a ...interface{}) error {
return lf.writeLevelMsg(LevelWarn, format, a...)
}

func (lf *LogFile) Error(msg string) error {
return lf.writeLevelMsg(msg, LevelError)
func (lf *LogFile) Error(format string, a ...interface{}) error {
return lf.writeLevelMsg(LevelError, format, a...)
}

func (lf *LogFile) Fatal(msg string) error {
return lf.writeLevelMsg(msg, LevelFatal)
func (lf *LogFile) Fatal(format string, a ...interface{}) error {
return lf.writeLevelMsg(LevelFatal, format, a...)
}

func (lf *LogFile) writeLevelMsg(msg string, level Priority) error {
func (lf *LogFile) writeLevelMsg(level Priority, format string, a ...interface{}) error {
if lf.probability < 1.0 && rand.Float32() > lf.probability {
// 按照概率写入
return nil
}

if level >= lf.level {
msg := fmt.Sprintf(format, a...)
return lf.Write(levelTitle[level] + " " + msg)
}

return nil
}

6 changes: 3 additions & 3 deletions level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (

func TestLevelWrite(t *testing.T) {
infoFile := NewLevelLog("/tmp/test-info.log", LevelInfo)
infoFile.Debug("hello world")
infoFile.Info("hello world")
infoFile.Error("hello world")
infoFile.Debug("hello %s", "world")
infoFile.Info("hello %d", 123)
infoFile.Error("hello %x", &t)

time.Sleep(time.Second * 2)
}

0 comments on commit 5ed5755

Please sign in to comment.