Skip to content

Commit

Permalink
优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
alex cai committed Nov 8, 2016
1 parent b6f12cb commit c42946b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ go get -u github.com/ibbd-dev/go-async-log

- 多个日志文件写入:例如错误信息一个文件,测试信息一个文件等
- 日志自动切割:前期支持按小时或者天切割
- 支持批量写入:最小单位为秒,不同的文件可以设置不同的写入频率(周期性写入,程序挂掉的时候最多可能会丢一个周期的数据,重要数据不能采用该方式
- 支持批量写入:最小单位为100毫秒,不同的文件可以设置不同的写入频率(周期性写入,程序挂掉的时候最多可能会丢一个周期的数据,重要数据不能采用该方式
- 同时支持实时写入文件,使用文件系统缓存(只要系统不挂,就不会有问题)
- 错误等级实现
- 可以写入json数据
Expand Down
26 changes: 18 additions & 8 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ func init() {
files: make(map[string]*LogFile),
}

timer := time.NewTicker(time.Second)
timer := time.NewTicker(time.Millisecond * 100)
//timer := time.NewTicker(time.Second)
go func() {
for {
select {
Expand Down Expand Up @@ -174,13 +175,11 @@ func (lf *LogFile) Write(msg string) error {
}

if lf.cache.use {
lf.writeMutex.Lock()
lf.cache.data = append(lf.cache.data, msg)
lf.writeMutex.Unlock()
lf.appendCache(msg)
return nil
}

return lf.directWrite(msg)
return lf.directWrite([]byte(msg))
}

// WriteJson 写入json数据
Expand All @@ -195,11 +194,22 @@ func (lf *LogFile) WriteJson(data interface{}) error {
return err
}

return lf.Write(string(bts))
if lf.cache.use {
lf.appendCache(string(bts))
return nil
}

return lf.directWrite(bts)
}

//*********************** 以下是私有函数 ************************************

func (lf *LogFile) appendCache(msg string) {
lf.writeMutex.Lock()
lf.cache.data = append(lf.cache.data, msg)
lf.writeMutex.Unlock()
}

// 同步缓存到文件中
func (lf *LogFile) flush() error {
lf.sync.status = statusDoing
Expand Down Expand Up @@ -245,7 +255,7 @@ func (lf *LogFile) getFilenameSuffix() string {
}

// 直接写入日志文件
func (lf *LogFile) directWrite(msg string) error {
func (lf *LogFile) directWrite(msg []byte) error {
file, err := lf.openFile()
//file, err := lf.openFileNoCache()
if err != nil {
Expand All @@ -254,7 +264,7 @@ func (lf *LogFile) directWrite(msg string) error {
defer file.Close()

lf.writeMutex.Lock()
_, err = file.WriteString(msg)
_, err = file.Write(msg)
lf.writeMutex.Unlock()

return err
Expand Down

0 comments on commit c42946b

Please sign in to comment.