Zack Williams | 41513bf | 2018-07-07 20:08:35 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017-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 | */ |
Stephane Barbarie | 3559506 | 2018-02-08 08:34:39 -0500 | [diff] [blame] | 16 | package common |
| 17 | |
| 18 | import ( |
| 19 | "github.com/evalphobia/logrus_fluent" |
| 20 | "github.com/sirupsen/logrus" |
| 21 | "net" |
| 22 | "strconv" |
| 23 | "sync" |
| 24 | ) |
| 25 | |
| 26 | type logManager struct { |
| 27 | *logrus.Logger |
| 28 | } |
| 29 | |
| 30 | // Singleton instance |
| 31 | var mgrInstance *logManager |
| 32 | var once sync.Once |
| 33 | |
| 34 | func (mgr *logManager) SetFluentd(fluentdHost string) { |
| 35 | var hook *logrus_fluent.FluentHook |
| 36 | var err error |
| 37 | var host string |
| 38 | var portStr string |
| 39 | var port int |
| 40 | |
| 41 | if host, portStr, err = net.SplitHostPort(fluentdHost); err != nil { |
| 42 | mgr.WithFields(logrus.Fields{ |
| 43 | "error": err.Error(), |
| 44 | }).Error("Failed to retrieve host/port information") |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | if port, err = strconv.Atoi(portStr); err != nil { |
| 49 | mgr.WithFields(logrus.Fields{ |
| 50 | "error": err.Error(), |
| 51 | }).Error("Failed to convert port to integer") |
| 52 | return |
| 53 | } |
| 54 | |
| 55 | if hook, err = logrus_fluent.NewWithConfig( |
| 56 | logrus_fluent.Config{ |
| 57 | Host: host, |
| 58 | Port: port, |
| 59 | }); err != nil { |
| 60 | mgr.WithFields(logrus.Fields{ |
| 61 | "error": err.Error(), |
| 62 | }).Error("Failed to enable Fluentd hook") |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | hook.SetTag("ponsim") |
| 67 | |
| 68 | hook.SetLevels([]logrus.Level{ |
| 69 | logrus.DebugLevel, |
| 70 | }) |
| 71 | |
| 72 | mgr.AddHook(hook) |
| 73 | |
| 74 | mgr.WithFields(logrus.Fields{ |
| 75 | "hook": hook, |
| 76 | }).Info("Added fluentd hook") |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Get instance |
| 81 | * |
| 82 | * It should get initialized only once |
| 83 | */ |
| 84 | func Logger() *logManager { |
| 85 | once.Do(func() { |
| 86 | |
| 87 | _logger := logrus.New() |
| 88 | _logger.Formatter = new(logrus.JSONFormatter) |
| 89 | _logger.Level = logrus.DebugLevel |
| 90 | //_logger.Out = |
| 91 | |
| 92 | mgrInstance = &logManager{_logger} |
| 93 | }) |
| 94 | |
| 95 | return mgrInstance |
| 96 | } |