Skip to content

Commit 01d7870

Browse files
committed
修复日志丢失问题
1 parent ae4f537 commit 01d7870

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

log/log_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
package log
22

33
import (
4+
"os"
45
"testing"
56
"time"
67
)
78

9+
const (
10+
testLogFile = "./test.log"
11+
)
12+
813
func TestLog(t *testing.T) {
914
Debug("default log begin")
1015
Infof("%v test log", time.Now())
@@ -18,6 +23,8 @@ func TestLog(t *testing.T) {
1823
l.Errorf("logger no color %v yyyyyy", time.Now().UnixNano())
1924
Infof("%v default has color test log", time.Now())
2025

21-
l.SetOutputFile("./vvv.log").SetRolling(true)
26+
l.SetOutputFile(testLogFile).SetRolling(true)
2227
l.Info(time.Now())
28+
os.Remove(testLogFile)
29+
2330
}

log/writer.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os"
88
"runtime"
99
"sync"
10+
"syscall"
1011
"time"
1112
)
1213

@@ -114,16 +115,22 @@ func (l *Logger) caller() (string, string) {
114115
}
115116

116117
func (l *Logger) rotate(now time.Time) {
118+
fmt.Printf("now:%v, fileTime:%v\n", now, l.fileTime)
117119
if !l.rolling || l.file == nil || now.Before(l.fileTime) {
118120
return
119121
}
120122

121123
l.out.Flush()
122-
l.file.Close()
123124

124-
oldFile := l.fileName + "." + time.Now().AddDate(0, 0, -1).Format("20060102")
125+
oldFile := l.fileName + "." + now.AddDate(0, 0, -1).Format("20060102")
126+
127+
syscall.Flock(int(l.file.Fd()), syscall.LOCK_EX)
128+
if _, err := os.Stat(oldFile); err != nil {
129+
os.Rename(l.fileName, oldFile)
130+
}
131+
syscall.Flock(int(l.file.Fd()), syscall.LOCK_UN)
125132

126-
os.Rename(l.fileName, oldFile)
133+
l.file.Close()
127134

128135
l.SetOutputFile(l.fileName)
129136
}

0 commit comments

Comments
 (0)