-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
102 lines (90 loc) · 2.11 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
99
100
101
102
package logger
import (
"fmt"
"os"
"strings"
log "github.com/sirupsen/logrus"
"time"
)
type Params map[string]interface{}
func InitLogger(dsn string) error {
log.SetFormatter(&log.TextFormatter{})
log.SetOutput(os.Stdout)
if err := InitSentry(dsn); err != nil {
return err
}
return nil
}
type Msg struct {
Message string
Params map[string]interface{}
}
func (msg *Msg) String() string {
if len(msg.Params) > 0 {
return fmt.Sprintf("%s - %v", msg.Message, msg.Params)
}
return fmt.Sprintf(msg.Message)
}
func Info(args ...interface{}) {
if len(args) == 0 {
Panic("call to logger.Info with no arguments")
}
msg := getMessage(args...)
log.WithFields(msg.Params).Info(msg.Message)
}
func Debug(args ...interface{}) {
if len(args) == 0 {
Panic("call to logger.Debug with no arguments")
}
msg := getMessage(args...)
log.WithFields(msg.Params).Debug(msg.Message)
}
func Warn(args ...interface{}) {
if len(args) == 0 {
Panic("call to logger.Warn with no arguments")
}
msg := getMessage(args...)
log.WithFields(msg.Params).Warn(msg.Message)
}
func getMessage(args ...interface{}) *Msg {
msg := &Msg{Params: make(Params)}
var generic []string
var message []string
for _, arg := range args {
switch arg := arg.(type) {
case nil:
continue
case string:
message = append(message, arg)
case Params:
appendMap(msg.Params, arg)
case map[string]interface{}:
appendMap(msg.Params, arg)
default:
generic = append(generic, fmt.Sprintf("%v", arg))
}
}
if len(message) > 0 {
msg.Message = strings.Join(message[:], ": ")
}
if len(generic) > 0 {
msg.Params["objects"] = strings.Join(generic[:], " | ")
}
return msg
}
func appendMap(root map[string]interface{}, tmp map[string]interface{}) {
for k, v := range tmp {
root[k] = v
}
}
func LogRequest(stop time.Duration, currency, request string, mustBeLogged bool) {
if stop > (time.Second * 2) {
Error("Response time exception", Params{
"currency": currency,
"request": request,
"time": stop.String(),
})
} else if mustBeLogged {
SendMessage(request + ": currency - " + currency + " time - " + stop.String())
}
}