forked from lavanet/lava
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lavalog.go
328 lines (302 loc) · 9.92 KB
/
lavalog.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package utils
import (
"context"
"fmt"
"os"
"runtime/debug"
"sort"
"strconv"
"strings"
"time"
sdkerrors "cosmossdk.io/errors"
"github.com/cometbft/cometbft/libs/log"
sdk "github.com/cosmos/cosmos-sdk/types"
zerolog "github.com/rs/zerolog"
zerologlog "github.com/rs/zerolog/log"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
EventPrefix = "lava_"
)
const (
LAVA_LOG_DEBUG = iota
LAVA_LOG_INFO
LAVA_LOG_WARN
LAVA_LOG_ERROR
LAVA_LOG_FATAL
LAVA_LOG_PANIC
NoColor = true
)
var (
JsonFormat = false
// if set to production, this will replace some errors to warning that can be caused by misuse instead of bugs
ExtendedLogLevel = "development"
rollingLogLogger = zerolog.New(os.Stderr).Level(zerolog.Disabled) // this is the singleton rolling logger.
globalLogLevel = zerolog.DebugLevel
)
type Attribute struct {
Key string
Value interface{}
}
func StringMapToAttributes(details map[string]string) []Attribute {
var attrs []Attribute
for key, val := range details {
attrs = append(attrs, Attribute{Key: key, Value: val})
}
return attrs
}
func LogAttr(key string, value interface{}) Attribute {
return Attribute{Key: key, Value: value}
}
func LogLavaEvent(ctx sdk.Context, logger log.Logger, name string, attributes map[string]string, description string) {
attributes_str := ""
eventAttrs := []sdk.Attribute{}
for key, val := range attributes {
attributes_str += fmt.Sprintf("%s: %s,", key, val)
eventAttrs = append(eventAttrs, sdk.NewAttribute(key, val))
}
sort.Slice(eventAttrs, func(i, j int) bool {
return eventAttrs[i].Key < eventAttrs[j].Key
})
logger.Info(fmt.Sprintf("%s%s:%s %s", EventPrefix, name, description, attributes_str))
ctx.EventManager().EmitEvent(sdk.NewEvent(EventPrefix+name, eventAttrs...))
}
func getLogLevel(logLevel string) zerolog.Level {
switch logLevel {
case "debug":
return zerolog.DebugLevel
case "info":
return zerolog.InfoLevel
case "warn":
return zerolog.WarnLevel
case "error":
return zerolog.ErrorLevel
case "fatal":
return zerolog.FatalLevel
default:
return zerolog.InfoLevel
}
}
func SetGlobalLoggingLevel(logLevel string) {
// setting global level prevents us from having two different levels for example one for stdout and one for rolling log.
// zerolog.SetGlobalLevel(getLogLevel(logLevel))
globalLogLevel = getLogLevel(logLevel)
LavaFormatInfo("setting log level", Attribute{Key: "loglevel", Value: logLevel})
}
func RollingLoggerSetup(rollingLogLevel string, filePath string, maxSize string, maxBackups string, maxAge string, stdFormat string) func() {
maxSizeNumber, err := strconv.Atoi(maxSize)
if err != nil {
LavaFormatFatal("strconv.Atoi(maxSize)", err, LogAttr("maxSize", maxSize))
}
maxBackupsNumber, err := strconv.Atoi(maxBackups)
if err != nil {
LavaFormatFatal("strconv.Atoi(maxSize)", err, LogAttr("maxBackups", maxBackups))
}
maxAgeNumber, err := strconv.Atoi(maxAge)
if err != nil {
LavaFormatFatal("strconv.Atoi(maxSize)", err, LogAttr("maxAge", maxAge))
}
rollingLogOutput := &lumberjack.Logger{
Filename: filePath,
MaxSize: maxSizeNumber,
MaxBackups: maxBackupsNumber,
MaxAge: maxAgeNumber,
Compress: true,
}
var logLevel zerolog.Level
switch rollingLogLevel {
case "off":
return func() {} // default is disabled.
case "debug":
logLevel = zerolog.DebugLevel
case "info":
logLevel = zerolog.InfoLevel
case "warn":
logLevel = zerolog.WarnLevel
case "error":
logLevel = zerolog.ErrorLevel
case "fatal":
logLevel = zerolog.FatalLevel
default:
LavaFormatFatal("unsupported case for rollingLoggerSetup", nil, LogAttr("rollingLogLevel", rollingLogLevel))
}
// set the rolling log level.
if stdFormat == "json" {
rollingLogLogger = zerolog.New(rollingLogOutput).Level(logLevel).With().Timestamp().Logger()
} else {
rollingLogLogger = zerolog.New(zerolog.ConsoleWriter{Out: rollingLogOutput, NoColor: NoColor, TimeFormat: time.Stamp}).Level(logLevel).With().Timestamp().Logger()
}
rollingLogLogger.Debug().Msg("Starting Rolling Logger")
return func() { rollingLogOutput.Close() }
}
func StrValueForLog(val interface{}, key string, idx int, attributes []Attribute) string {
st_val := ""
switch value := val.(type) {
case context.Context:
// we don't want to print the whole context so change it
switch key {
case "GUID":
guid, found := GetUniqueIdentifier(value)
if found {
st_val = strconv.FormatUint(guid, 10)
attributes[idx] = Attribute{Key: key, Value: guid}
} else {
attributes[idx] = Attribute{Key: key, Value: "no-guid"}
}
default:
attributes[idx] = Attribute{Key: key, Value: "context-masked"}
}
default:
st_val = StrValue(val)
}
return st_val
}
func StrValue(val interface{}) string {
st_val := ""
switch value := val.(type) {
case context.Context:
// we don't want to print the whole context so change it
case bool:
if value {
st_val = "true"
} else {
st_val = "false"
}
case fmt.Stringer:
st_val = value.String()
case string:
st_val = value
case int:
st_val = strconv.Itoa(value)
case int64:
st_val = strconv.FormatInt(value, 10)
case uint64:
st_val = strconv.FormatUint(value, 10)
case error:
st_val = value.Error()
case []string:
st_val = strings.Join(value, ",")
// needs to come after stringer so byte inheriting objects will use their string method if implemented (like AccAddress)
case []byte:
st_val = string(value)
case nil:
st_val = ""
default:
st_val = fmt.Sprintf("%+v", value)
}
return st_val
}
func LavaFormatLog(description string, err error, attributes []Attribute, severity uint) error {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
if JsonFormat {
zerologlog.Logger = zerologlog.Output(os.Stderr).Level(globalLogLevel)
} else {
zerologlog.Logger = zerologlog.Output(zerolog.ConsoleWriter{Out: os.Stderr, NoColor: NoColor, TimeFormat: time.Stamp}).Level(globalLogLevel)
}
var logEvent *zerolog.Event
var rollingLoggerEvent *zerolog.Event
switch severity {
case LAVA_LOG_PANIC:
// prefix = "Panic:"
logEvent = zerologlog.Panic()
if rollingLogLogger.GetLevel() != zerolog.Disabled {
rollingLoggerEvent = rollingLogLogger.Panic()
}
case LAVA_LOG_FATAL:
// prefix = "Fatal:"
logEvent = zerologlog.Fatal()
if rollingLogLogger.GetLevel() != zerolog.Disabled {
rollingLoggerEvent = rollingLogLogger.Fatal()
}
case LAVA_LOG_ERROR:
// prefix = "Error:"
logEvent = zerologlog.Error()
rollingLoggerEvent = rollingLogLogger.Error()
case LAVA_LOG_WARN:
// prefix = "Warning:"
logEvent = zerologlog.Warn()
rollingLoggerEvent = rollingLogLogger.Warn()
case LAVA_LOG_INFO:
logEvent = zerologlog.Info()
rollingLoggerEvent = rollingLogLogger.Info()
// prefix = "Info:"
case LAVA_LOG_DEBUG:
logEvent = zerologlog.Debug()
rollingLoggerEvent = rollingLogLogger.Debug()
// prefix = "Debug:"
}
output := description
attrStrings := []string{}
if err != nil {
logEvent = logEvent.Err(err)
rollingLoggerEvent = rollingLoggerEvent.Err(err)
output = fmt.Sprintf("%s ErrMsg: %s", output, err.Error())
}
if len(attributes) > 0 {
for idx, attr := range attributes {
key := attr.Key
val := attr.Value
st_val := StrValueForLog(val, key, idx, attributes)
logEvent = logEvent.Str(key, st_val)
rollingLoggerEvent = rollingLoggerEvent.Str(key, st_val)
attrStrings = append(attrStrings, fmt.Sprintf("%s:%s", attr.Key, st_val))
}
attributesStr := "{" + strings.Join(attrStrings, ",") + "}"
output = fmt.Sprintf("%s %+v", output, attributesStr)
}
logEvent.Msg(description)
rollingLoggerEvent.Msg(description)
// here we return the same type of the original error message, this handles nil case as well
errRet := sdkerrors.Wrap(err, output)
if errRet == nil { // we always want to return an error if lavaFormatError was called
return fmt.Errorf(output)
}
return errRet
}
func LavaFormatPanic(description string, err error, attributes ...Attribute) {
attributes = append(attributes, Attribute{Key: "StackTrace", Value: debug.Stack()})
LavaFormatLog(description, err, attributes, LAVA_LOG_PANIC)
}
func LavaFormatFatal(description string, err error, attributes ...Attribute) {
attributes = append(attributes, Attribute{Key: "StackTrace", Value: debug.Stack()})
LavaFormatLog(description, err, attributes, LAVA_LOG_FATAL)
}
// depending on the build flag, this log function will log either a warning or an error.
// the purpose of this function is to fail E2E tests and not allow unexpected behavior to reach main.
// while in production some errors may occur as consumers / providers might set up their processes in the wrong way.
// in test environment we dont expect to have these errors and if they occur we would like to fail the test.
func LavaFormatProduction(description string, err error, attributes ...Attribute) error {
if ExtendedLogLevel == "production" {
return LavaFormatWarning(description, err, attributes...)
} else {
return LavaFormatError(description, err, attributes...)
}
}
func LavaFormatError(description string, err error, attributes ...Attribute) error {
return LavaFormatLog(description, err, attributes, LAVA_LOG_ERROR)
}
func LavaFormatWarning(description string, err error, attributes ...Attribute) error {
return LavaFormatLog(description, err, attributes, LAVA_LOG_WARN)
}
func LavaFormatInfo(description string, attributes ...Attribute) error {
return LavaFormatLog(description, nil, attributes, LAVA_LOG_INFO)
}
func LavaFormatDebug(description string, attributes ...Attribute) error {
return LavaFormatLog(description, nil, attributes, LAVA_LOG_DEBUG)
}
func FormatStringerList[T fmt.Stringer](description string, listToPrint []T, separator string) string {
st := ""
for _, printable := range listToPrint {
st = st + separator + printable.String() + "\n"
}
st = fmt.Sprintf(description+"\n\t%s", st)
return st
}
func FormatLongString(msg string, maxCharacters int) string {
if maxCharacters != 0 && len(msg) > maxCharacters {
postfixLen := maxCharacters / 3
prefixLen := maxCharacters - postfixLen
return msg[:prefixLen] + "...truncated..." + msg[len(msg)-postfixLen:]
}
return msg
}