Skip to content

Commit

Permalink
增加json数据写入
Browse files Browse the repository at this point in the history
  • Loading branch information
alex cai committed Nov 4, 2016
1 parent 32ae01a commit eb1436b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ go get -u github.com/ibbd-dev/go-async-log
- 支持批量写入:最小单位为秒,不同的文件可以设置不同的写入频率(周期性写入,程序挂掉的时候最多可能会丢一个周期的数据,重要数据不能采用该方式
- 同时支持实时写入文件,使用文件系统缓存(只要系统不挂,就不会有问题)
- 错误等级实现
- 可以写入json数据

## 配置项

Expand Down
13 changes: 12 additions & 1 deletion log.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package asyncLog

import (
"encoding/json"
"log"
"os"
"strings"
Expand Down Expand Up @@ -150,7 +151,7 @@ func (lf *LogFile) SetUseCache(useCache bool) {
lf.cache.use = useCache
}

// 写缓存
// Write 写缓存
func (lf *LogFile) Write(msg string) error {
if lf.flag == StdFlag {
msg = time.Now().Format(logTimeFormat) + " " + msg + newlineChar
Expand All @@ -168,6 +169,16 @@ func (lf *LogFile) Write(msg string) error {
return lf.directWrite(msg)
}

// WriteJson 写入json数据
func (lf *LogFile) WriteJson(data interface{}) error {
bts, err := json.Marshal(data)
if err != nil {
return err
}

return lf.Write(string(bts))
}

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

// 同步缓存到文件中
Expand Down
9 changes: 9 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ func TestNewLogFile(t *testing.T) {
_ = lf1.Write("lf1: ---hello world3")
_ = lf1.Write("lf1: ---hello world4")

var hello = struct {
Hello string
World int
}{
Hello: "test",
World: 12,
}
_ = lf1.WriteJson(hello)

time.Sleep(time.Second * 2)
}

Expand Down

0 comments on commit eb1436b

Please sign in to comment.