/
logger.go
98 lines (84 loc) · 1.99 KB
/
logger.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
package util
import (
"bytes"
"fmt"
"os"
"runtime"
"strings"
"github.com/demisto/alfred/conf"
"github.com/Sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)
var maxLineSize int
var output *lumberjack.Logger
type captainHook struct {
}
func (*captainHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (*captainHook) Fire(entry *logrus.Entry) error {
skip := 6
ok := true
var file string
var line int
for ok {
_, file, line, ok = runtime.Caller(skip)
if strings.Contains(file, "logrus") {
skip++
} else {
entry.Data["source"] = fmt.Sprintf("%s:%d", file, line)
return nil
}
}
return nil
}
type simpleFormatter struct {
}
func (*simpleFormatter) Format(entry *logrus.Entry) ([]byte, error) {
buff := new(bytes.Buffer)
buff.Grow(512)
buff.WriteString(entry.Time.Format("2006-01-02 15:04:05.9999 "))
msg := entry.Message
if len(msg) > maxLineSize {
msg = fmt.Sprintf("%s...\nNOTE, too much data to log, message was truncated.", msg[:maxLineSize])
}
fmt.Fprintf(buff, "%s %s ", entry.Level, msg)
for name, field := range entry.Data {
fmt.Fprintf(buff, "(%s: %v)", name, field)
}
buff.WriteString(" \n")
if runtime.GOOS == "windows" {
buff.WriteString("\r")
}
return buff.Bytes(), nil
}
// InitLog - init the log for server
func InitLog(fileloc string, logLevel string, stdout bool) {
// limit the size of the message to log
maxLineSize = 100000
level, err := logrus.ParseLevel(logLevel)
if err != nil {
fmt.Printf("Invalid log level value provided; %s, using Info", logLevel)
level = logrus.InfoLevel
}
logrus.SetLevel(level)
logrus.AddHook(new(captainHook))
logrus.SetFormatter(new(simpleFormatter))
if stdout {
logrus.SetOutput(os.Stderr)
} else {
SetOutput(fileloc)
}
conf.LogWriter = logrus.StandardLogger().Writer()
}
//SetOutput ...
func SetOutput(fileloc string) {
if output == nil {
output = &lumberjack.Logger{}
logrus.SetOutput(output)
}
output.Filename = fileloc
output.MaxSize = 10
output.MaxBackups = 3
output.MaxAge = 0
}