@@ -10,8 +10,9 @@ import (
10
10
"time"
11
11
)
12
12
13
- // fileNameTimeFormat 文件名称格式
14
- const fileNameTimeFormat = "2006-01-02"
13
+ // timeFormat 时间格式
14
+ // 用于文件名称格式
15
+ const timeFormat = "2006-01-02"
15
16
16
17
// FileWriter 文件写入结构体
17
18
type FileWriter struct {
@@ -33,13 +34,13 @@ func NewFileWriter(opts ...Option) (*FileWriter, error) {
33
34
var filename string
34
35
var err error
35
36
for {
36
- filename = p .getFilenameAccordingToTimestamp ()
37
+ filename = p .getFilename ()
37
38
_ , err := os .Stat (filename )
38
39
if err != nil {
39
40
if os .IsNotExist (err ) {
40
41
if p .num > 0 {
41
42
p .num --
42
- filename = p .getFilenameAccordingToTimestamp ()
43
+ filename = p .getFilename ()
43
44
}
44
45
//文件不存在
45
46
break
@@ -76,15 +77,15 @@ func (p *FileWriter) write() {
76
77
77
78
func (p * FileWriter ) checkFile () {
78
79
info , _ := p .file .Stat ()
79
- if strings .Index (p .file .Name (), time .Now ().Format (fileNameTimeFormat )) < 0 ||
80
+ if strings .Index (p .file .Name (), time .Now ().Format (timeFormat )) < 0 ||
80
81
(p .opts .cap > 0 && uint (info .Size ()) > p .opts .cap ) {
81
82
//生成新文件
82
83
if uint (info .Size ()) > p .opts .cap {
83
84
p .num ++
84
85
} else {
85
86
p .num = 0
86
87
}
87
- filename := p .getFilenameAccordingToTimestamp ()
88
+ filename := p .getFilename ()
88
89
_ = p .file .Close ()
89
90
p .file , _ = os .OpenFile (filename , os .O_WRONLY | os .O_APPEND | os .O_CREATE | os .O_SYNC , 0600 )
90
91
}
@@ -105,20 +106,21 @@ func (p *FileWriter) Write(data []byte) (n int, err error) {
105
106
return n , nil
106
107
}
107
108
108
- // getFilenameAccordingToTimestamp 通过日期命名log文件
109
- func (p * FileWriter ) getFilenameAccordingToTimestamp () string {
109
+ // getFilename 获取log文件名
110
+ // 目前为:以日期格式命名,eg:2006-01-02.log or 2006-01-02.log
111
+ func (p * FileWriter ) getFilename () string {
110
112
if p .FilenameFunc != nil {
111
113
return p .FilenameFunc (p )
112
114
}
113
115
if p .opts .cap == 0 {
114
116
return filepath .Join (p .opts .path ,
115
117
fmt .Sprintf ("%s.%s" ,
116
- time .Now ().Format (fileNameTimeFormat ),
118
+ time .Now ().Format (timeFormat ),
117
119
p .opts .suffix ))
118
120
}
119
121
return filepath .Join (p .opts .path ,
120
122
fmt .Sprintf ("%s-[%d].%s" ,
121
- time .Now ().Format (fileNameTimeFormat ),
123
+ time .Now ().Format (timeFormat ),
122
124
p .num ,
123
125
p .opts .suffix ))
124
126
}
0 commit comments