File: happyDevFormatter.go

package info (click to toggle)
golang-github-mgutz-logxi 1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 524 kB
  • sloc: makefile: 7
file content (373 lines) | stat: -rw-r--r-- 8,983 bytes parent folder | download
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package log

import (
	"encoding/json"
	"fmt"
	"io"
	"runtime/debug"
	"strings"

	"github.com/mgutz/ansi"
)

// colorScheme defines a color theme for HappyDevFormatter
type colorScheme struct {
	Key     string
	Message string
	Value   string
	Misc    string
	Source  string

	Trace string
	Debug string
	Info  string
	Warn  string
	Error string
}

var indent = "  "
var maxCol = defaultMaxCol
var theme *colorScheme

func parseKVList(s, separator string) map[string]string {
	pairs := strings.Split(s, separator)
	if len(pairs) == 0 {
		return nil
	}
	m := map[string]string{}
	for _, pair := range pairs {
		if pair == "" {
			continue
		}
		parts := strings.Split(pair, "=")
		switch len(parts) {
		case 1:
			m[parts[0]] = ""
		case 2:
			m[parts[0]] = parts[1]
		}
	}
	return m
}

func parseTheme(theme string) *colorScheme {
	m := parseKVList(theme, ",")
	cs := &colorScheme{}
	var wildcard string

	var color = func(key string) string {
		if disableColors {
			return ""
		}
		style := m[key]
		c := ansi.ColorCode(style)
		if c == "" {
			c = wildcard
		}
		//fmt.Printf("plain=%b [%s] %s=%q\n", ansi.DefaultFG, key, style, c)

		return c
	}
	wildcard = color("*")

	if wildcard != ansi.Reset {
		cs.Key = wildcard
		cs.Value = wildcard
		cs.Misc = wildcard
		cs.Source = wildcard
		cs.Message = wildcard

		cs.Trace = wildcard
		cs.Debug = wildcard
		cs.Warn = wildcard
		cs.Info = wildcard
		cs.Error = wildcard
	}

	cs.Key = color("key")
	cs.Value = color("value")
	cs.Misc = color("misc")
	cs.Source = color("source")
	cs.Message = color("message")

	cs.Trace = color("TRC")
	cs.Debug = color("DBG")
	cs.Warn = color("WRN")
	cs.Info = color("INF")
	cs.Error = color("ERR")
	return cs
}

// HappyDevFormatter is the formatter used for terminals. It is
// colorful, dev friendly and provides meaningful logs when
// warnings and errors occur.
//
// HappyDevFormatter does not worry about performance. It's at least 3-4X
// slower than JSONFormatter since it delegates to JSONFormatter to marshal
// then unmarshal JSON. Then it does other stuff like read source files, sort
// keys all to give a developer more information.
//
// SHOULD NOT be used in production for extended period of time. However, it
// works fine in SSH terminals and binary deployments.
type HappyDevFormatter struct {
	name string
	col  int
	// always use the production formatter
	jsonFormatter *JSONFormatter
}

// NewHappyDevFormatter returns a new instance of HappyDevFormatter.
func NewHappyDevFormatter(name string) *HappyDevFormatter {
	jf := NewJSONFormatter(name)
	return &HappyDevFormatter{
		name:          name,
		jsonFormatter: jf,
	}
}

func (hd *HappyDevFormatter) writeKey(buf bufferWriter, key string) {
	// assumes this is not the first key
	hd.writeString(buf, Separator)
	if key == "" {
		return
	}
	buf.WriteString(theme.Key)
	hd.writeString(buf, key)
	hd.writeString(buf, AssignmentChar)
	if !disableColors {
		buf.WriteString(ansi.Reset)
	}
}

func (hd *HappyDevFormatter) set(buf bufferWriter, key string, value interface{}, color string) {
	var str string
	if s, ok := value.(string); ok {
		str = s
	} else if s, ok := value.(fmt.Stringer); ok {
		str = s.String()
	} else {
		str = fmt.Sprintf("%v", value)
	}
	val := strings.Trim(str, "\n ")
	if (isPretty && key != "") || hd.col+len(key)+2+len(val) >= maxCol {
		buf.WriteString("\n")
		hd.col = 0
		hd.writeString(buf, indent)
	}
	hd.writeKey(buf, key)
	if color != "" {
		buf.WriteString(color)
	}
	hd.writeString(buf, val)
	if color != "" && !disableColors {
		buf.WriteString(ansi.Reset)
	}
}

// Write a string and tracks the position of the string so we can break lines
// cleanly. Do not send ANSI escape sequences, just raw strings
func (hd *HappyDevFormatter) writeString(buf bufferWriter, s string) {
	buf.WriteString(s)
	hd.col += len(s)
}

func (hd *HappyDevFormatter) getContext(color string) string {
	if disableCallstack {
		return ""
	}
	frames := parseDebugStack(string(debug.Stack()), 5, true)
	if len(frames) == 0 {
		return ""
	}
	for _, frame := range frames {
		context := frame.String(color, theme.Source)
		if context != "" {
			return context
		}
	}
	return ""
}

func (hd *HappyDevFormatter) getLevelContext(level int, entry map[string]interface{}) (message string, context string, color string) {

	switch level {
	case LevelTrace:
		color = theme.Trace
		context = hd.getContext(color)
		context += "\n"
	case LevelDebug:
		color = theme.Debug
	case LevelInfo:
		color = theme.Info
	// case LevelWarn:
	// 	color = theme.Warn
	// 	context = hd.getContext(color)
	// 	context += "\n"
	case LevelWarn, LevelError, LevelFatal:

		// warnings return an error but if it does not have an error
		// then print line info only
		if level == LevelWarn {
			color = theme.Warn
			kv := entry[KeyMap.CallStack]
			if kv == nil {
				context = hd.getContext(color)
				context += "\n"
				break
			}
		} else {
			color = theme.Error
		}

		if disableCallstack || contextLines == -1 {
			context = trimDebugStack(string(debug.Stack()))
			break
		}
		frames := parseLogxiStack(entry, 4, true)
		if frames == nil {
			frames = parseDebugStack(string(debug.Stack()), 4, true)
		}

		if len(frames) == 0 {
			break
		}
		errbuf := pool.Get()
		defer pool.Put(errbuf)
		lines := 0
		for _, frame := range frames {
			err := frame.readSource(contextLines)
			if err != nil {
				// by setting to empty, the original stack is used
				errbuf.Reset()
				break
			}
			ctx := frame.String(color, theme.Source)
			if ctx == "" {
				continue
			}
			errbuf.WriteString(ctx)
			errbuf.WriteRune('\n')
			lines++
		}
		context = errbuf.String()
	default:
		panic("should never get here")
	}
	return message, context, color
}

// Format a log entry.
func (hd *HappyDevFormatter) Format(writer io.Writer, level int, msg string, args []interface{}) {
	buf := pool.Get()
	defer pool.Put(buf)

	if len(args) == 1 {
		args = append(args, 0)
		copy(args[1:], args[0:])
		args[0] = singleArgKey
	}

	// warn about reserved, bad and complex keys
	for i := 0; i < len(args); i += 2 {
		isReserved, err := isReservedKey(args[i])
		if err != nil {
			InternalLog.Error("Key is not a string.", "err", fmt.Errorf("args[%d]=%v", i, args[i]))
		} else if isReserved {
			InternalLog.Fatal("Key conflicts with reserved key. Avoiding using single rune keys.", "key", args[i].(string))
		} else {
			// Ensure keys are simple strings. The JSONFormatter doesn't escape
			// keys as a performance tradeoff. This panics if the JSON key
			// value has a different value than a simple quoted string.
			key := args[i].(string)
			b, err := json.Marshal(key)
			if err != nil {
				panic("Key is invalid. " + err.Error())
			}
			if string(b) != `"`+key+`"` {
				panic("Key is complex. Use simpler key for: " + fmt.Sprintf("%q", key))
			}
		}
	}

	// use the production JSON formatter to format the log first. This
	// ensures JSON will marshal/unmarshal correctly in production.
	entry := hd.jsonFormatter.LogEntry(level, msg, args)

	// reset the column tracker used for fancy formatting
	hd.col = 0

	// timestamp
	buf.WriteString(theme.Misc)
	hd.writeString(buf, entry[KeyMap.Time].(string))
	if !disableColors {
		buf.WriteString(ansi.Reset)
	}

	// emphasize warnings and errors
	message, context, color := hd.getLevelContext(level, entry)
	if message == "" {
		message = entry[KeyMap.Message].(string)
	}

	// DBG, INF ...
	hd.set(buf, "", entry[KeyMap.Level].(string), color)
	// logger name
	hd.set(buf, "", entry[KeyMap.Name], theme.Misc)
	// message from user
	hd.set(buf, "", message, theme.Message)

	// Preserve key order in the sequencethey were added by developer.This
	// makes it easier for developers to follow the log.
	order := []string{}
	lenArgs := len(args)
	for i := 0; i < len(args); i += 2 {
		if i+1 >= lenArgs {
			continue
		}
		if key, ok := args[i].(string); ok {
			order = append(order, key)
		} else {
			order = append(order, badKeyAtIndex(i))
		}
	}

	for _, key := range order {
		// skip reserved keys which were already added to buffer above
		isReserved, err := isReservedKey(key)
		if err != nil {
			panic("key is invalid. Should never get here. " + err.Error())
		} else if isReserved {
			continue
		}
		hd.set(buf, key, entry[key], theme.Value)
	}

	addLF := true
	hasCallStack := entry[KeyMap.CallStack] != nil
	// WRN,ERR file, line number context

	if context != "" {
		// warnings and traces are single line, space can be optimized
		if level == LevelTrace || (level == LevelWarn && !hasCallStack) {
			// gets rid of "in "
			idx := strings.IndexRune(context, 'n')
			hd.set(buf, "in", context[idx+2:], color)
		} else {
			buf.WriteRune('\n')
			if !disableColors {
				buf.WriteString(color)
			}
			addLF = context[len(context)-1:len(context)] != "\n"
			buf.WriteString(context)
			if !disableColors {
				buf.WriteString(ansi.Reset)
			}
		}
	} else if hasCallStack {
		hd.set(buf, "", entry[KeyMap.CallStack], color)
	}
	if addLF {
		buf.WriteRune('\n')
	}
	buf.WriteTo(writer)
}