generated from layer5io/layer5-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 94
/
logger.go
107 lines (89 loc) · 2.4 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
103
104
105
106
107
package logger
import (
"os"
"time"
"github.com/go-logr/logr"
"github.com/layer5io/meshkit/errors"
"github.com/sirupsen/logrus"
gormlogger "gorm.io/gorm/logger"
)
type Handler interface {
Info(description ...interface{})
Debug(description ...interface{})
Warn(err error)
Error(err error)
// Kubernetes Controller compliant logger
ControllerLogger() logr.Logger
DatabaseLogger() gormlogger.Interface
}
type Logger struct {
handler *logrus.Entry
}
// TerminalFormatter is exported
type TerminalFormatter struct{}
// Format defined the format of output for Logrus logs
// Format is exported
func (f *TerminalFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return append([]byte(entry.Message), '\n'), nil
}
func New(appname string, opts Options) (Handler, error) {
log := logrus.New()
switch opts.Format {
case JsonLogFormat:
log.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.RFC3339,
})
case SyslogLogFormat:
log.SetFormatter(&logrus.TextFormatter{
TimestampFormat: time.RFC3339,
FullTimestamp: true,
})
case TerminalLogFormat:
log.SetFormatter(new(TerminalFormatter))
}
// log.SetReportCaller(true)
log.SetOutput(os.Stdout)
if opts.Output != nil {
log.SetOutput(opts.Output)
}
log.SetLevel(logrus.InfoLevel)
if opts.DebugLevel {
log.SetLevel(logrus.DebugLevel)
}
entry := log.WithFields(logrus.Fields{"app": appname})
return &Logger{handler: entry}, nil
}
func (l *Logger) Error(err error) {
if err == nil {
return
}
l.handler.WithFields(logrus.Fields{
"code": errors.GetCode(err),
"severity": errors.GetSeverity(err),
"short-description": errors.GetSDescription(err),
"probable-cause": errors.GetCause(err),
"suggested-remediation": errors.GetRemedy(err),
}).Log(logrus.ErrorLevel, err.Error())
}
func (l *Logger) Info(description ...interface{}) {
l.handler.Log(logrus.InfoLevel,
description...,
)
}
func (l *Logger) Debug(description ...interface{}) {
l.handler.Log(logrus.DebugLevel,
description...,
)
}
func (l *Logger) Warn(err error) {
if err == nil {
return
}
l.handler.WithFields(logrus.Fields{
"code": errors.GetCode(err),
"severity": errors.GetSeverity(err),
"short-description": errors.GetSDescription(err),
"probable-cause": errors.GetCause(err),
"suggested-remediation": errors.GetRemedy(err),
}).Log(logrus.WarnLevel, err.Error())
}