blob: 15b2de9af1a4446babf38bafa909b08ce47b559a [file] [log] [blame]
Zack Williams41513bf2018-07-07 20:08:35 -07001/*
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 Barbarie35595062018-02-08 08:34:39 -050016package common
17
18import (
19 "github.com/evalphobia/logrus_fluent"
20 "github.com/sirupsen/logrus"
21 "net"
22 "strconv"
23 "sync"
24)
25
26type logManager struct {
27 *logrus.Logger
28}
29
30// Singleton instance
31var mgrInstance *logManager
32var once sync.Once
33
34func (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 */
84func 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}