-
Notifications
You must be signed in to change notification settings - Fork 20
/
init.go
83 lines (75 loc) · 1.44 KB
/
init.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
package ppp
import (
"fmt"
"github.com/panjjo/ppp/db"
"github.com/sirupsen/logrus"
"runtime"
"strings"
)
// DBPool 数据库连接池实例
var DBPool *db.Pool
// NewLogger 创建log 记录
func NewLogger(str string) {
level, _ := logrus.ParseLevel(str)
logrus.SetLevel(level)
logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "01-02 15:04:05"})
logrus.AddHook(newlogHook())
}
func init(){
logrus.SetLevel(logrus.DebugLevel)
}
// NewDBPool 创建数据库连接池
func NewDBPool(config *db.Config) {
DBPool = db.GetPool(config)
}
func newlogHook(levels ...logrus.Level)logrus.Hook{
hook := &loghook{
skip:8,
field:"file",
levels: levels,
}
if len(levels) == 0 {
hook.levels = logrus.AllLevels
}
return hook
}
type loghook struct {
skip int
field string
levels []logrus.Level
}
func (h *loghook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (h *loghook) Fire(e *logrus.Entry) error {
e.Data["file"] = findCaller(8)
return nil
}
func findCaller(skip int) string {
file := ""
line := 0
for i := 0; i < 10; i++ {
file, line = getCaller(skip + i)
if !strings.HasPrefix(file, "logrus") {
break
}
}
return fmt.Sprintf("%s:%d", file, line)
}
func getCaller(skip int) (string, int) {
_, file, line, ok := runtime.Caller(skip)
if !ok {
return "", 0
}
n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}
return file, line
}