/
root.go
112 lines (91 loc) · 2.63 KB
/
root.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
106
107
108
109
110
111
package mpt_log
import (
"github.com/dipperin/dipperin-core/third-party/log"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"os"
"path/filepath"
"os/user"
)
// Predefined handlers
var (
root log.Logger
StdoutHandler = log.StreamHandler(os.Stdout, log.LogfmtFormat())
StderrHandler = log.StreamHandler(os.Stderr, log.LogfmtFormat())
)
func init() {
if isatty.IsTerminal(os.Stdout.Fd()) {
StdoutHandler = log.StreamHandler(colorable.NewColorableStdout(), log.TerminalFormat())
}
if isatty.IsTerminal(os.Stderr.Fd()) {
StderrHandler = log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat())
}
root = log.New()
// default output nothing
root.SetHandler(log.LvlFilterHandler(log.LvlCrit, StdoutHandler))
}
// Root returns the root logger
func Root() log.Logger {
return root
}
// The following functions bypass the exported logger methods (logger.Debug,
// etc.) to keep the call depth the same for all paths to logger.write so
// runtime.Caller(2) always refers to the call site in client code.
// Debug is a convenient alias for Root().Debug
func Debug(msg string, ctx ...interface{}) {
root.Debug(msg, ctx...)
}
// Info is a convenient alias for Root().Info
func Info(msg string, ctx ...interface{}) {
root.Info(msg, ctx...)
}
// Warn is a convenient alias for Root().Warn
func Warn(msg string, ctx ...interface{}) {
root.Warn(msg, ctx...)
}
// Error is a convenient alias for Root().Error
func Error(msg string, ctx ...interface{}) {
root.Error(msg, ctx...)
}
// Crit is a convenient alias for Root().Crit
func Crit(msg string, ctx ...interface{}) {
root.Crit(msg, ctx...)
}
func homeDir() string {
if home := os.Getenv("HOME"); home != "" {
return home
}
if usr, err := user.Current(); err == nil {
return usr.HomeDir
}
return ""
}
// 外边可能要文件输出,可能要控制台输出,可能两个都需要
func InitMptLogger(logLevel log.Lvl, nodeName string, removeOld bool) {
targetDir := filepath.Join(homeDir(), "tmp", "cs_debug", "mpt")
if !PathExists(targetDir) {
os.MkdirAll(targetDir, os.ModePerm)
}
var handlers []log.Handler
logFilePath := filepath.Join(targetDir, nodeName + ".log")
if removeOld {
os.RemoveAll(logFilePath)
}
fileHandler, err := log.FileHandler(logFilePath, log.LogfmtFormat())
if err != nil {
panic(err)
}
log.Debug("write mpt debug log to file", "path", logFilePath)
handlers = append(handlers, log.LvlFilterHandler(logLevel, fileHandler))
Root().SetHandler(log.MultiHandler(handlers...))
}
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}