-
Notifications
You must be signed in to change notification settings - Fork 0
/
timebasedwriter.go
85 lines (76 loc) · 1.63 KB
/
timebasedwriter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package hyperlog
import (
"errors"
"fmt"
"os"
"time"
)
const (
FormatYear = "2006"
FormatMonth = "2006_01"
FormatDate = "2006_01_02"
DateMode TimeMode = iota
MonthMode
YearMode
)
type TimeMode int
type TimeBasedWriter struct {
Directory string
Extension string
FilePrefix string
FileSuffix string
Mode TimeMode
Log LogEngine
currentFileName string
currentFile *os.File
}
func (lfw *TimeBasedWriter) getFile() *os.File {
t := ""
now := time.Now()
switch lfw.Mode {
case DateMode:
t = now.Format(FormatDate)
case MonthMode:
t = now.Format(FormatMonth)
case YearMode:
t = now.Format(FormatYear)
default:
t = now.Format(FormatYear)
}
fileName := fmt.Sprintf("%s%s%s%s%s.%s", lfw.Directory, string(os.PathSeparator), lfw.FilePrefix, t, lfw.FileSuffix, lfw.Extension)
if lfw.currentFileName != fileName {
if lfw.currentFile != nil {
err := lfw.currentFile.Close()
if err != nil {
panic("can not close log file")
}
}
} else {
if lfw.currentFile != nil {
return lfw.currentFile
}
}
if _, err := os.Stat(fileName); err != nil && errors.Is(err, os.ErrNotExist) {
file, err := os.Create(fileName)
if err != nil {
panic("can not create log file " + fileName)
}
lfw.currentFile = file
lfw.currentFileName = fileName
return file
}
file, err := os.Open(fileName)
if err != nil {
panic("can not open log file " + fileName)
}
lfw.currentFile = file
lfw.currentFileName = fileName
return file
}
func (lfw *TimeBasedWriter) Write(p []byte) (n int, err error) {
f := lfw.getFile()
if f != nil {
return f.Write(p)
}
return 0, fmt.Errorf("can not nil file to write log")
}