-
Notifications
You must be signed in to change notification settings - Fork 2
/
init_helper.go
105 lines (85 loc) · 2.31 KB
/
init_helper.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
98
99
100
101
102
103
104
105
package logger
import (
"fmt"
"gopkg.in/natefinch/lumberjack.v2"
"io"
"os"
"path/filepath"
)
// logLevel:
// 0->DEBUG
// 1->INFO
// 2->NOTICE
// 3->WARN
// 4->ERROR
// logFileName:
// typically application name is used
// logFileDir:
// the directory where log files dump to
// maxLogFileSize:
// in megabytes, 100 by default
// maxLogFileBackups:
// max file backups, 3 by default
// maxLogFileAge:
// max log file ages, in days. 30 by default
func Init(logLevel int, logFileName string, logFileDir string, maxLogFileSize, maxLogFileBackups, maxLogFileAge int) {
if len(logFileDir) == 0 {
InitLogger(logLevel)
Infof("[logger] log path is not set")
return
}
dirExists, _ := dirExists(logFileDir)
if !dirExists {
InitLogger(logLevel)
Warnf("[logger] log path '%s' does NOT exist", logFileDir)
return
}
maxSize := maxLogFileSize
maxBackups := maxLogFileBackups
maxAge := maxLogFileAge
if maxSize <= 0 {
maxSize = 100
}
if maxBackups <= 0 {
maxBackups = 3
}
if maxAge <= 0 {
maxAge = 30
}
stdOutputFile = &lumberjack.Logger{
Filename: filepath.Join(logFileDir, fmt.Sprintf("%s.log", logFileName)),
MaxSize: maxSize, // megabytes
MaxBackups: maxBackups,
MaxAge: maxAge, //days
LocalTime: true,
}
errOutputFile = &lumberjack.Logger{
Filename: filepath.Join(logFileDir, fmt.Sprintf("%s-error.log", logFileName)),
MaxSize: maxSize, // megabytes
MaxBackups: maxBackups,
MaxAge: maxAge, //days
LocalTime: true,
}
stdOutput := io.MultiWriter(stdOutputFile, os.Stdout)
errOutput := io.MultiWriter(errOutputFile, os.Stderr)
InitLoggerWithOutput(stdOutput, errOutput, logLevel)
}
func InitRotateLogger(logLevel int, logFileName string, logFileDir string, maxLogFileSize, maxLogFileBackups, maxLogFileAge int, rotateStrategy int) {
rotateLog = true
if rotateStrategy != RotateStrategyPerHour && rotateStrategy != RotateStrategyPerDay {
panic(fmt.Sprintf("invalid parameter rotateStrategy: unsupported value %d", rotateStrategy))
}
rotateLogStrategy = rotateStrategy
Init(logLevel, logFileName, logFileDir, maxLogFileSize, maxLogFileBackups, maxLogFileAge)
}
func dirExists(filePath string) (bool, error) {
if _, err := os.Stat(filePath); err == nil {
return true, nil
} else {
if os.IsNotExist(err) {
return false, err
} else {
return true, err
}
}
}