-
Notifications
You must be signed in to change notification settings - Fork 24
/
log.go
98 lines (87 loc) · 2.38 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
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
/*
* Copyright © 2017 Xiao Zhang <zzxx513@gmail.com>.
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file.
*/
package turbo
import (
"io"
"os"
"path"
"runtime"
"strings"
logger "github.com/sirupsen/logrus"
)
var log *logger.Logger
// ContextHook is a hook to be fired when logging on the logging levels returned from
// `Levels()` on your implementation of the interface. Note that this is not
// fired in a goroutine or a channel with workers, you should handle such
// functionality yourself if your call is non-blocking and you don't wish for
// the logging calls for levels returned from `Levels()` to block.
//
// The original hook interface is:
// type Hook interface {
// Levels() []Level
// Fire(*Entry) error
// }
type ContextHook struct{}
// Levels returns active log levels
func (hook ContextHook) Levels() []logger.Level {
return logger.AllLevels
}
// Fire is for adding file, func and line info to logger.
func (hook ContextHook) Fire(entry *logger.Entry) error {
pc := make([]uintptr, 3, 3)
cnt := runtime.Callers(7, pc)
for i := 0; i < cnt; i++ {
pci := pc[i] - 1
fu := runtime.FuncForPC(pci)
name := fu.Name()
if !strings.Contains(name, "github.com/Sirupsen/logrus") {
file, line := fu.FileLine(pci)
entry.Data["file"] = path.Base(file)
entry.Data["func"] = path.Base(name)
entry.Data["line"] = line
break
}
}
return nil
}
func setupLoggerFile(c *Config) {
logPath := c.configs[turboLogPath]
wd, e := os.Getwd()
if e != nil {
panic(e)
}
if len(strings.TrimSpace(logPath)) == 0 {
logPath = wd
}
if !path.IsAbs(logPath) {
logPath = wd + "/" + logPath
}
logPath = path.Clean(logPath)
err := os.MkdirAll(logPath, 0755)
panicIf(err)
file, err := os.OpenFile(logPath+"/turbo.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
panicIf(err)
logger.SetOutput(file)
}
func initLogger(c *Config) {
if c.Env() == "production" {
setupLoggerFile(c)
// Log as JSON instead of the default ASCII formatter.
logger.SetFormatter(&logger.JSONFormatter{})
logger.SetLevel(logger.InfoLevel)
} else {
logger.SetFormatter(&logger.TextFormatter{})
logger.SetOutput(os.Stderr)
logger.SetLevel(logger.DebugLevel)
logger.AddHook(ContextHook{})
}
log = logger.StandardLogger()
}
// SetOutput sets output at runtime
func SetOutput(out io.Writer) {
log.Out = out
log.Formatter = &logger.TextFormatter{}
}