forked from yeabow/cat-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
97 lines (78 loc) · 1.98 KB
/
logger.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
86
87
88
89
90
91
92
93
94
95
96
97
package cat
import (
"fmt"
"io"
"log"
"os"
"sync"
"time"
)
type Logger struct {
logger *log.Logger
mu sync.Mutex
currentDay int
}
func createLogger() *Logger {
now := time.Now()
var writer = getWriterByTime(now)
return &Logger{
logger: log.New(writer, "", log.LstdFlags),
mu: sync.Mutex{},
currentDay: now.Day(),
}
}
func openLoggerFile(time time.Time) (*os.File, error) {
filename := loggerFileName(time)
return os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
}
func loggerFileName(time time.Time) string {
year, month, day := time.Date()
filename := fmt.Sprintf("%s/go_cat_%d%02d%02d.log", config.baseLogDir, year, month, day)
return filename
}
func getWriterByTime(time time.Time) io.Writer {
if file, err := openLoggerFile(time); err != nil {
var filename string
if file == nil {
filename = loggerFileName(time)
}
log.Printf("Cannot open log file: %s, logs will be redirected to stdout", filename)
return os.Stdout
} else {
log.Printf("Log has been redirected to the file: %s", file.Name())
return file
}
}
func (l *Logger) switchLogFile(time time.Time) {
l.mu.Lock()
defer l.mu.Unlock()
if l.currentDay == time.Day() {
return
}
l.logger.SetOutput(getWriterByTime(time))
}
func (l *Logger) changeLogFile() {
l.mu.Lock()
defer l.mu.Unlock()
l.logger.SetOutput(getWriterByTime(time.Now()))
}
func (l *Logger) write(prefix, format string, args ...interface{}) {
now := time.Now()
if now.Day() != l.currentDay {
l.switchLogFile(now)
}
l.logger.Printf(prefix+" "+format, args...)
}
func (l *Logger) Debug(format string, args ...interface{}) {
l.write("[Debug]", format, args...)
}
func (l *Logger) Info(format string, args ...interface{}) {
l.write("[Info]", format, args...)
}
func (l *Logger) Warning(format string, args ...interface{}) {
l.write("[Warning]", format, args...)
}
func (l *Logger) Error(format string, args ...interface{}) {
l.write("[Error]", format, args...)
}
var logger = createLogger()