Skip to content

Commit

Permalink
按概率写入只对json和level日志有效
Browse files Browse the repository at this point in the history
  • Loading branch information
alex cai committed Nov 8, 2016
1 parent 8d10415 commit a414263
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
9 changes: 9 additions & 0 deletions level.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package asyncLog

import (
"math/rand"
)

// 日志优先级
type Priority int

Expand Down Expand Up @@ -58,6 +62,11 @@ func (lf *LogFile) Fatal(msg string) error {
}

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

if level >= lf.level {
return lf.Write(levelTitle[level] + " " + msg)
}
Expand Down
20 changes: 11 additions & 9 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ const (
// 异步日志变量
var asyncLog *asyncLogType

var nowFunc = time.Now

func init() {
asyncLog = &asyncLogType{
files: make(map[string]*LogFile),
Expand All @@ -106,7 +108,7 @@ func init() {
for {
select {
case <-timer.C:
//now := time.Now()
//now := nowFunc()
for _, file := range asyncLog.files {
if file.sync.status != statusDoing {
go file.flush()
Expand Down Expand Up @@ -165,13 +167,8 @@ func (lf *LogFile) SetProbability(probability float32) {

// Write 写缓存
func (lf *LogFile) Write(msg string) error {
if lf.probability < 1.0 && rand.Float32() > lf.probability {
// 按照概率写入
return nil
}

if lf.flag == StdFlag {
msg = time.Now().Format(logTimeFormat) + " " + msg + newlineChar
msg = nowFunc().Format(logTimeFormat) + " " + msg + newlineChar
} else {
msg = msg + newlineChar
}
Expand All @@ -188,6 +185,11 @@ func (lf *LogFile) Write(msg string) error {

// WriteJson 写入json数据
func (lf *LogFile) WriteJson(data interface{}) error {
if lf.probability < 1.0 && rand.Float32() > lf.probability {
// 按照概率写入
return nil
}

bts, err := json.Marshal(data)
if err != nil {
return err
Expand Down Expand Up @@ -237,9 +239,9 @@ func (lf *LogFile) flush() error {
// 获取文件名的后缀
func (lf *LogFile) getFilenameSuffix() string {
if lf.logRotate.rotate == RotateDate {
return time.Now().Format("20060102")
return nowFunc().Format("20060102")
}
return time.Now().Format("2006010215")
return nowFunc().Format("2006010215")
}

// 直接写入日志文件
Expand Down

0 comments on commit a414263

Please sign in to comment.