-
Notifications
You must be signed in to change notification settings - Fork 50
/
handler_iowriter.go
89 lines (71 loc) · 2.48 KB
/
handler_iowriter.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
package log
import (
"fmt"
"io"
"time"
"github.com/justtrackio/gosoline/pkg/cfg"
)
func init() {
AddHandlerFactory("iowriter", handlerIoWriterFactory)
}
type HandlerIoWriterSettings struct {
Level string `cfg:"level" default:"info"`
Channels []string `cfg:"channels"`
Formatter string `cfg:"formatter" default:"console"`
TimestampFormat string `cfg:"timestamp_format" default:"15:04:05.000"`
Writer string `cfg:"writer" default:"stdout"`
}
func handlerIoWriterFactory(config cfg.Config, name string) (Handler, error) {
handlerConfigKey := getHandlerConfigKey(name)
settings := &HandlerIoWriterSettings{}
UnmarshalHandlerSettingsFromConfig(config, name, settings)
var ok bool
var err error
var writerFactory IoWriterWriterFactory
var writer io.Writer
var formatter Formatter
if writerFactory, ok = ioWriterFactories[settings.Writer]; !ok {
return nil, fmt.Errorf("io writer of type %s not available", settings.Writer)
}
if writer, err = writerFactory(config, handlerConfigKey); err != nil {
return nil, fmt.Errorf("can not create io writer of type %s: %w", settings.Writer, err)
}
if formatter, ok = formatters[settings.Formatter]; !ok {
return nil, fmt.Errorf("io writer formatter of type %s not available", settings.Formatter)
}
return NewHandlerIoWriter(settings.Level, settings.Channels, formatter, settings.TimestampFormat, writer), nil
}
type handlerIoWriter struct {
level int
channels []string
formatter Formatter
timestampFormat string
writer io.Writer
}
func NewHandlerIoWriter(level string, channels []string, formatter Formatter, timestampFormat string, writer io.Writer) *handlerIoWriter {
return &handlerIoWriter{
level: LevelPriority(level),
channels: channels,
formatter: formatter,
timestampFormat: timestampFormat,
writer: writer,
}
}
func (h *handlerIoWriter) Channels() []string {
return h.channels
}
func (h *handlerIoWriter) Level() int {
return h.level
}
func (h *handlerIoWriter) Log(timestamp time.Time, level int, msg string, args []interface{}, logErr error, data Data) error {
var err error
var bytes []byte
timestampStr := timestamp.Format(h.timestampFormat)
if bytes, err = h.formatter(timestampStr, level, msg, args, logErr, data); err != nil {
return fmt.Errorf("can not format log message: %w", err)
}
if _, err = h.writer.Write(bytes); err != nil {
return fmt.Errorf("can not write log message: %w", err)
}
return nil
}