Matteo Scandolo | 88e9189 | 2018-11-06 16:29:19 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 3 | |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package logger |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | |
| 22 | lkh "github.com/gfremex/logrus-kafka-hook" |
| 23 | log "github.com/sirupsen/logrus" |
| 24 | ) |
| 25 | |
| 26 | var ( |
| 27 | myLogger *log.Entry |
| 28 | ) |
| 29 | |
| 30 | func Setup(kafkaBroker string, level string) { |
| 31 | |
| 32 | logger := log.New() |
| 33 | myLogger = logger.WithField("topics", []string{"bbsim.log"}) |
| 34 | |
| 35 | // TODO make this configurable via cli arg |
| 36 | if level == "DEBUG" { |
| 37 | logger.SetLevel(log.DebugLevel) |
| 38 | } |
| 39 | |
| 40 | if len(kafkaBroker) > 0 { |
| 41 | myLogger.Debug("Setting up kafka integration") |
| 42 | hook, err := lkh.NewKafkaHook( |
| 43 | "kh", |
| 44 | []log.Level{log.DebugLevel, log.InfoLevel, log.WarnLevel, log.ErrorLevel}, |
| 45 | &log.JSONFormatter{ |
| 46 | FieldMap: log.FieldMap{ |
| 47 | log.FieldKeyTime: "@timestamp", |
| 48 | log.FieldKeyLevel: "level", |
| 49 | log.FieldKeyMsg: "message", |
| 50 | }, |
| 51 | }, |
| 52 | []string{kafkaBroker}, |
| 53 | ) |
| 54 | |
| 55 | if err != nil { |
| 56 | myLogger.Error(err) |
| 57 | } |
| 58 | |
| 59 | logger.Hooks.Add(hook) |
| 60 | |
| 61 | } |
| 62 | |
| 63 | myLogger.WithField("kafkaBroker", kafkaBroker).Debug("Logger setup done") |
| 64 | } |
| 65 | |
| 66 | func WithField(key string, value interface{}) *log.Entry { |
| 67 | return myLogger.WithField(key, value) |
| 68 | } |
| 69 | |
| 70 | func WithFields(fields log.Fields) *log.Entry { |
| 71 | return myLogger.WithFields(fields) |
| 72 | } |
| 73 | |
| 74 | func Panic(args ...interface{}) { |
| 75 | myLogger.Panic(fmt.Sprint(args...)) |
| 76 | } |
| 77 | |
| 78 | func Fatal(args ...interface{}) { |
| 79 | myLogger.Fatal(fmt.Sprint(args...)) |
| 80 | } |
| 81 | |
| 82 | func Error(args ...interface{}) { |
| 83 | myLogger.Error(fmt.Sprint(args...)) |
| 84 | } |
| 85 | |
| 86 | func Warn(args ...interface{}) { |
| 87 | myLogger.Warn(fmt.Sprint(args...)) |
| 88 | } |
| 89 | |
| 90 | func Info(args ...interface{}) { |
| 91 | myLogger.Info(fmt.Sprint(args...)) |
| 92 | } |
| 93 | |
| 94 | func Debug(args ...interface{}) { |
| 95 | myLogger.Debug(fmt.Sprint(args...)) |
| 96 | } |