-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathformatter.go
76 lines (62 loc) · 1.75 KB
/
formatter.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
package slog
import "runtime"
//
// Formatter interface
//
// Formatter interface
type Formatter interface {
// Format you can format record and write result to record.Buffer
Format(record *Record) ([]byte, error)
}
// FormatterFunc wrapper definition
type FormatterFunc func(r *Record) ([]byte, error)
// Format a log record
func (fn FormatterFunc) Format(r *Record) ([]byte, error) {
return fn(r)
}
// Formattable interface
type Formattable interface {
// Formatter get the log formatter
Formatter() Formatter
// SetFormatter set the log formatter
SetFormatter(Formatter)
}
// FormattableTrait alias of FormatterWrapper
type FormattableTrait = FormatterWrapper
// FormatterWrapper use for format log record.
// default use the TextFormatter
type FormatterWrapper struct {
// if not set, default use the TextFormatter
formatter Formatter
}
// Formatter get formatter. if not set, will return TextFormatter
func (f *FormatterWrapper) Formatter() Formatter {
if f.formatter == nil {
f.formatter = NewTextFormatter()
}
return f.formatter
}
// SetFormatter to handler
func (f *FormatterWrapper) SetFormatter(formatter Formatter) {
f.formatter = formatter
}
// Format log record to bytes
func (f *FormatterWrapper) Format(record *Record) ([]byte, error) {
return f.Formatter().Format(record)
}
// CallerFormatFn caller format func
type CallerFormatFn func(rf *runtime.Frame) (cs string)
// AsTextFormatter util func
func AsTextFormatter(f Formatter) *TextFormatter {
if tf, ok := f.(*TextFormatter); ok {
return tf
}
panic("slog: cannot cast input as *TextFormatter")
}
// AsJSONFormatter util func
func AsJSONFormatter(f Formatter) *JSONFormatter {
if jf, ok := f.(*JSONFormatter); ok {
return jf
}
panic("slog: cannot cast input as *JSONFormatter")
}