blob: 7749dd247b75a72270acee1b2aab528d7707fdeb [file] [log] [blame]
Stephane Barbarie35595062018-02-08 08:34:39 -05001package common
2
3import (
4 "github.com/evalphobia/logrus_fluent"
5 "github.com/sirupsen/logrus"
6 "net"
7 "strconv"
8 "sync"
9)
10
11type logManager struct {
12 *logrus.Logger
13}
14
15// Singleton instance
16var mgrInstance *logManager
17var once sync.Once
18
19func (mgr *logManager) SetFluentd(fluentdHost string) {
20 var hook *logrus_fluent.FluentHook
21 var err error
22 var host string
23 var portStr string
24 var port int
25
26 if host, portStr, err = net.SplitHostPort(fluentdHost); err != nil {
27 mgr.WithFields(logrus.Fields{
28 "error": err.Error(),
29 }).Error("Failed to retrieve host/port information")
30 return
31 }
32
33 if port, err = strconv.Atoi(portStr); err != nil {
34 mgr.WithFields(logrus.Fields{
35 "error": err.Error(),
36 }).Error("Failed to convert port to integer")
37 return
38 }
39
40 if hook, err = logrus_fluent.NewWithConfig(
41 logrus_fluent.Config{
42 Host: host,
43 Port: port,
44 }); err != nil {
45 mgr.WithFields(logrus.Fields{
46 "error": err.Error(),
47 }).Error("Failed to enable Fluentd hook")
48 return
49 }
50
51 hook.SetTag("ponsim")
52
53 hook.SetLevels([]logrus.Level{
54 logrus.DebugLevel,
55 })
56
57 mgr.AddHook(hook)
58
59 mgr.WithFields(logrus.Fields{
60 "hook": hook,
61 }).Info("Added fluentd hook")
62}
63
64/**
65 * Get instance
66 *
67 * It should get initialized only once
68 */
69func Logger() *logManager {
70 once.Do(func() {
71
72 _logger := logrus.New()
73 _logger.Formatter = new(logrus.JSONFormatter)
74 _logger.Level = logrus.DebugLevel
75 //_logger.Out =
76
77 mgrInstance = &logManager{_logger}
78 })
79
80 return mgrInstance
81}