diff --git a/README.md b/README.md index 50e3a30..5167029 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ go get -u github.com/ibbd-dev/go-async-log - 支持批量写入:最小单位为秒,不同的文件可以设置不同的写入频率(周期性写入,程序挂掉的时候最多可能会丢一个周期的数据,重要数据不能采用该方式 - 同时支持实时写入文件,使用文件系统缓存(只要系统不挂,就不会有问题) - 错误等级实现 +- 可以写入json数据 ## 配置项 diff --git a/log.go b/log.go index 51f1492..a67652d 100644 --- a/log.go +++ b/log.go @@ -1,6 +1,7 @@ package asyncLog import ( + "encoding/json" "log" "os" "strings" @@ -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 @@ -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)) +} + //*********************** 以下是私有函数 ************************************ // 同步缓存到文件中 diff --git a/log_test.go b/log_test.go index 6c70f34..cf8b980 100644 --- a/log_test.go +++ b/log_test.go @@ -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) }