Skip to content

Commit

Permalink
fix 换行符问题 and 不使用缓存只能写第一条的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
alex cai committed Nov 10, 2016
1 parent 472652c commit a5c968f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
12 changes: 7 additions & 5 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ const (
fileFlag = os.O_WRONLY | os.O_CREATE | os.O_APPEND

// 换行符
newlineChar = "\n"
newlineStr = "\n"
newlineChar = '\n'

// 缓存切片的初始容量
cacheInitCap = 64
Expand Down Expand Up @@ -171,9 +172,9 @@ func (lf *LogFile) SetProbability(probability float32) {
// Write 写缓存
func (lf *LogFile) Write(msg string) error {
if lf.flag == StdFlag {
msg = nowFunc().Format(logTimeFormat) + " " + msg + newlineChar
msg = nowFunc().Format(logTimeFormat) + " " + msg + newlineStr
} else {
msg = msg + newlineChar
msg = msg + newlineStr
}

if lf.cache.use {
Expand All @@ -195,9 +196,10 @@ func (lf *LogFile) WriteJson(data interface{}) error {
if err != nil {
return err
}
bts = append(bts, newlineChar)

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

Expand Down Expand Up @@ -263,7 +265,7 @@ func (lf *LogFile) directWrite(msg []byte) error {
if err != nil {
panic(err)
}
defer file.Close()
//defer file.Close()

lf.logRotate.mutex.Lock()
_, err = file.Write(msg)
Expand Down
8 changes: 8 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ func TestNewLogFile(t *testing.T) {
_ = lf1.Write("lf1: ---hello world3")
_ = lf1.Write("lf1: ---hello world4")

time.Sleep(time.Second * 2)
}

func TestJson(t *testing.T) {
lf1 := NewLogFile("/tmp/test-json.log")
lf1.SetFlags(NoFlag)
lf1.SetUseCache(false)

var hello = struct {
Hello string
World int
Expand Down

0 comments on commit a5c968f

Please sign in to comment.