/
log.go
71 lines (62 loc) · 1.45 KB
/
log.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
package mylog
import (
"fmt"
"github.com/ritterhou/stinger/core/common"
"github.com/sirupsen/logrus"
"github.com/t-tomalak/logrus-easy-formatter"
"os"
"runtime"
"strings"
)
const evnFile = "env.txt"
var (
separator = "\n"
env = "production"
)
func init() {
if runtime.GOOS == "windows" {
separator = "\r\n"
}
path := common.GetAbsPath(evnFile)
if _, err := os.Stat(path); !os.IsNotExist(err) {
content := common.ReadFile(path)
env = string(content)
}
}
func InitLog(file string, level string) {
if env == "develop" {
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: false,
})
logrus.SetReportCaller(true)
} else {
logrus.SetFormatter(&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "%time% - [%lvl%] %msg%" + separator,
})
}
logLevel := logrus.InfoLevel
level = strings.ToUpper(level)
switch level {
case "DEBUG":
logLevel = logrus.DebugLevel
case "INFO":
logLevel = logrus.InfoLevel
case "WARN":
logLevel = logrus.WarnLevel
}
logrus.SetLevel(logLevel)
if file == "stdout" {
logrus.SetOutput(os.Stdout)
} else {
if _, err := os.Stat(file); !os.IsNotExist(err) {
os.Remove(file)
}
logFile, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
fmt.Println("open log file failed", err)
}
logrus.SetOutput(logFile)
}
fmt.Printf("### Log file is [%s], log level is [%s], env is [%s] ###\n", file, logrus.GetLevel().String(), env)
}