-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
log.go
75 lines (63 loc) · 1.78 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
package log
import (
"os"
"strings"
"github.com/hashicorp/terraform/flatmap"
"github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
)
var (
log = logrus.New()
rawLog = logrus.New()
translations = make(map[string]string)
)
// LoadTranslations takes a map[string]interface and flattens it to map[string]string
// Because translations have been loaded - we internally override log the formatter
// Nested entries are accessible using dot notation.
// example: `{"foo": {"bar": "baz"}}`
// flattened: `foo.bar: baz`
func LoadTranslations(thing map[string]interface{}) {
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = `Jan 02 15:04:05`
formatter.FullTimestamp = true
log.Formatter = &TranslationFormatter{formatter}
translations = flatmap.Flatten(thing)
}
type TranslationFormatter struct {
*prefixed.TextFormatter
}
func (t *TranslationFormatter) Format(entry *logrus.Entry) ([]byte, error) {
if code, ok := entry.Data["code"]; ok {
if translation, ok := translations[code.(string)]; ok {
entry.Message = translation
}
}
return t.TextFormatter.Format(entry)
}
type RawFormatter struct{}
func (f *RawFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return []byte(entry.Message), nil
}
func init() {
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = `Jan 02 15:04:05`
formatter.FullTimestamp = true
log.Formatter = formatter
rawLog.Formatter = new(RawFormatter)
}
func Get() *logrus.Logger {
switch strings.ToLower(os.Getenv("TYK_LOGLEVEL")) {
case "error":
log.Level = logrus.ErrorLevel
case "warn":
log.Level = logrus.WarnLevel
case "debug":
log.Level = logrus.DebugLevel
default:
log.Level = logrus.InfoLevel
}
return log
}
func GetRaw() *logrus.Logger {
return rawLog
}