-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
100 lines (86 loc) · 2.04 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
package logging
import (
"log"
"os"
"time"
"github.com/Sirupsen/logrus"
)
var (
standardFields logrus.Fields
logger *logrus.Logger
)
func init() {
logger = logrus.New()
logger.Formatter = customFormatter{&logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
}}
logger.Out = os.Stdout
}
// SetStandardFields sets up the service name, version, hostname and pid fields
func SetStandardFields(service, version string) {
hostname, _ := os.Hostname()
standardFields = logrus.Fields{
"service": service,
"version": version,
"hostname": hostname,
"pid": os.Getpid(),
}
}
// UsePrettyPrint tells the logger to print in human readable format
func UsePrettyPrint() {
logger.Formatter = customFormatter{&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.RFC3339Nano,
QuoteEmptyFields: true,
}}
}
// WarnLogger creates a logger that can plug in to an HTTP server
func WarnLogger() (basicLogger *log.Logger, dispose func()) {
w := logger.WriterLevel(logrus.WarnLevel)
basicLogger = log.New(w, "", 0)
dispose = func() {
w.Close()
}
return
}
// ErrorLogger creates a logger that can plug in to an HTTP server
func ErrorLogger() (basicLogger *log.Logger, dispose func()) {
w := logger.WriterLevel(logrus.ErrorLevel)
basicLogger = log.New(w, "", 0)
dispose = func() {
w.Close()
}
return
}
// Info logs an info level message with standard fields
func Info(msg, id string) {
if id == "" {
logger.Info(msg)
return
}
logger.WithField("request_id", id).Info(msg)
}
// Warn logs a warn level message with standard fields
func Warn(msg, id string) {
if id == "" {
logger.Warn(msg)
return
}
logger.WithField("request_id", id).Warn(msg)
}
// Error logs an error level message with standard fields
func Error(msg, id string) {
if id == "" {
logger.Error(msg)
return
}
logger.WithField("request_id", id).Error(msg)
}
// Fatal logs a fatal level message with standard fields
func Fatal(msg, id string) {
if id == "" {
logger.Fatal(msg)
return
}
logger.WithField("request_id", id).Fatal(msg)
}