github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/log/log.go (about) 1 package log 2 3 import ( 4 "os" 5 "strings" 6 7 "github.com/hashicorp/terraform/flatmap" 8 "github.com/sirupsen/logrus" 9 prefixed "github.com/x-cray/logrus-prefixed-formatter" 10 ) 11 12 var ( 13 log = logrus.New() 14 rawLog = logrus.New() 15 translations = make(map[string]string) 16 ) 17 18 // LoadTranslations takes a map[string]interface and flattens it to map[string]string 19 // Because translations have been loaded - we internally override log the formatter 20 // Nested entries are accessible using dot notation. 21 // example: `{"foo": {"bar": "baz"}}` 22 // flattened: `foo.bar: baz` 23 func LoadTranslations(thing map[string]interface{}) { 24 formatter := new(prefixed.TextFormatter) 25 formatter.TimestampFormat = `Jan 02 15:04:05` 26 formatter.FullTimestamp = true 27 log.Formatter = &TranslationFormatter{formatter} 28 translations = flatmap.Flatten(thing) 29 } 30 31 type TranslationFormatter struct { 32 *prefixed.TextFormatter 33 } 34 35 func (t *TranslationFormatter) Format(entry *logrus.Entry) ([]byte, error) { 36 if code, ok := entry.Data["code"]; ok { 37 if translation, ok := translations[code.(string)]; ok { 38 entry.Message = translation 39 } 40 } 41 return t.TextFormatter.Format(entry) 42 } 43 44 type RawFormatter struct{} 45 46 func (f *RawFormatter) Format(entry *logrus.Entry) ([]byte, error) { 47 return []byte(entry.Message), nil 48 } 49 50 func init() { 51 formatter := new(prefixed.TextFormatter) 52 formatter.TimestampFormat = `Jan 02 15:04:05` 53 formatter.FullTimestamp = true 54 55 log.Formatter = formatter 56 rawLog.Formatter = new(RawFormatter) 57 } 58 59 func Get() *logrus.Logger { 60 switch strings.ToLower(os.Getenv("TYK_LOGLEVEL")) { 61 case "error": 62 log.Level = logrus.ErrorLevel 63 case "warn": 64 log.Level = logrus.WarnLevel 65 case "debug": 66 log.Level = logrus.DebugLevel 67 default: 68 log.Level = logrus.InfoLevel 69 } 70 return log 71 } 72 73 func GetRaw() *logrus.Logger { 74 return rawLog 75 }