/
logger.go
187 lines (156 loc) · 4.64 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package logger
import (
"bytes"
"encoding/json"
"flag"
"os"
"strings"
"sync"
"time"
"github.com/RedHatInsights/cloud-connector/internal/domain"
clowder "github.com/redhatinsights/app-common-go/pkg/api/v1"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/redhatinsights/platform-go-middlewares/logging/cloudwatch"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// Log is an instance of the global logrus.Logger
var Log *logrus.Logger
var logLevel logrus.Level
var initializeLogger sync.Once
var cloudWatchHook *cloudwatch.Hook
func buildFormatter(format string) logrus.Formatter {
switch strings.ToUpper(format) {
case "TEXT":
return &logrus.TextFormatter{}
default:
return NewCloudwatchFormatter()
}
}
// NewCloudwatchFormatter creates a new log formatter
func NewCloudwatchFormatter() *CustomCloudwatch {
f := &CustomCloudwatch{}
var err error
if f.Hostname == "" {
if f.Hostname, err = os.Hostname(); err != nil {
f.Hostname = "unknown"
}
}
return f
}
//Format is the log formatter for the entry
func (f *CustomCloudwatch) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
now := time.Now()
hostname, err := os.Hostname()
if err == nil {
f.Hostname = hostname
}
data := map[string]interface{}{
"@timestamp": now.Format("2006-01-02T15:04:05.999Z"),
"@version": 1,
"message": entry.Message,
"levelname": entry.Level.String(),
"source_host": f.Hostname,
"app": "cloud-connector",
"caller": entry.Caller.Func.Name(),
}
for k, v := range entry.Data {
switch v := v.(type) {
case error:
data[k] = v.Error()
case Marshaler:
data[k] = v.MarshalLog()
default:
data[k] = v
}
}
j, err := json.Marshal(data)
if err != nil {
return nil, err
}
b.Write(j)
return b.Bytes(), nil
}
// InitLogger initializes the logger instance
func InitLogger() {
initializeLogger.Do(func() {
hostname, _ := os.Hostname()
logconfig := viper.New()
logconfig.SetDefault("LOG_LEVEL", "DEBUG")
logconfig.SetDefault("LOG_GROUP", "platform-dev")
logconfig.SetDefault("AWS_REGION", "us-east-1")
logconfig.SetDefault("LOG_STREAM", hostname)
logconfig.SetDefault("LOG_FORMAT", "text")
logconfig.SetDefault("LOG_BATCH_FREQUENCY", 10*time.Second)
logconfig.SetEnvPrefix("CLOUD_CONNECTOR")
logconfig.AutomaticEnv()
format := logconfig.GetString("LOG_FORMAT")
batchFrequency := logconfig.GetDuration("LOG_BATCH_FREQUENCY")
key := logconfig.GetString("CW_AWS_ACCESS_KEY_ID")
secret := logconfig.GetString("CW_AWS_SECRET_ACCESS_KEY")
region := logconfig.GetString("AWS_REGION")
group := logconfig.GetString("LOG_GROUP")
stream := logconfig.GetString("LOG_STREAM")
if clowder.IsClowderEnabled() {
cfg := clowder.LoadedConfig
key = cfg.Logging.Cloudwatch.AccessKeyId
secret = cfg.Logging.Cloudwatch.SecretAccessKey
region = cfg.Logging.Cloudwatch.Region
group = cfg.Logging.Cloudwatch.LogGroup
}
switch strings.ToUpper(logconfig.GetString("LOG_LEVEL")) {
case "TRACE":
logLevel = logrus.TraceLevel
case "DEBUG":
logLevel = logrus.DebugLevel
case "ERROR":
logLevel = logrus.ErrorLevel
default:
logLevel = logrus.InfoLevel
}
if flag.Lookup("test.v") != nil {
logLevel = logrus.FatalLevel
}
formatter := buildFormatter(format)
Log = &logrus.Logger{
Out: os.Stdout,
Level: logLevel,
Formatter: formatter,
Hooks: make(logrus.LevelHooks),
ReportCaller: true,
}
if key != "" {
Log.Infof("Configuring CloudWatch logging (level=%s, group=%s, stream=%s, batchFrequency=%d)",
logLevel, group, stream, batchFrequency)
cred := credentials.NewStaticCredentials(key, secret, "")
awsconf := aws.NewConfig().WithRegion(region).WithCredentials(cred)
cloudWatchHook, err := cloudwatch.NewBatchingHook(group, stream, awsconf, batchFrequency)
if err != nil {
Log.WithFields(logrus.Fields{"error": err}).Warn("Unable to configure CloudWatch hook")
}
Log.Hooks.Add(cloudWatchHook)
}
})
}
func FlushLogger() {
if cloudWatchHook != nil {
cloudWatchHook.Flush()
}
}
func LogFatalError(msg string, err error) {
Log.WithFields(logrus.Fields{"error": err}).Fatal(msg)
}
func LogError(msg string, err error) {
Log.WithFields(logrus.Fields{"error": err}).Error(msg)
}
func LogWithError(log *logrus.Entry, msg string, err error) {
log.WithFields(logrus.Fields{"error": err}).Error(msg)
}
func LogErrorWithAccountAndClientId(msg string, err error, account domain.AccountID, org_id domain.OrgID, client_id domain.ClientID) {
Log.WithFields(logrus.Fields{"error": err,
"account": account,
"org_id": org_id,
"client_id": client_id}).Error(msg)
}