-
Notifications
You must be signed in to change notification settings - Fork 50
/
logger_message_encode_handler.go
76 lines (57 loc) · 2.09 KB
/
logger_message_encode_handler.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 log
import (
"context"
"time"
"github.com/justtrackio/gosoline/pkg/cfg"
"github.com/justtrackio/gosoline/pkg/encoding/json"
"github.com/spf13/cast"
)
const MessageAttributeLoggerContext = "logger:context"
type MessageWithLoggingFieldsEncoder struct {
logger Logger
}
func NewMessageWithLoggingFieldsEncoder(_ cfg.Config, logger Logger) *MessageWithLoggingFieldsEncoder {
logger = NewSamplingLogger(logger, time.Minute)
return NewMessageWithLoggingFieldsEncoderWithInterfaces(logger)
}
func NewMessageWithLoggingFieldsEncoderWithInterfaces(logger Logger) *MessageWithLoggingFieldsEncoder {
return &MessageWithLoggingFieldsEncoder{
logger: logger,
}
}
func (m MessageWithLoggingFieldsEncoder) Encode(ctx context.Context, _ interface{}, attributes map[string]string) (context.Context, map[string]string, error) {
fields := GlobalContextFieldsResolver(ctx)
if len(fields) == 0 {
return ctx, attributes, nil
}
stringAble := make(map[string]interface{}, len(fields))
for k, v := range fields {
if _, err := cast.ToStringE(v); err != nil {
m.logger.Warn("omitting logger context field %s of type %T during message encoding", k, v)
continue
}
stringAble[k] = v
}
encodedFields, err := json.Marshal(stringAble)
if err != nil {
m.logger.Warn("can not json marshal logger context fields during message encoding")
return ctx, attributes, nil
}
attributes[MessageAttributeLoggerContext] = string(encodedFields)
return ctx, attributes, nil
}
func (m MessageWithLoggingFieldsEncoder) Decode(ctx context.Context, _ interface{}, attributes map[string]string) (context.Context, map[string]string, error) {
var ok bool
if _, ok = attributes[MessageAttributeLoggerContext]; !ok {
return ctx, attributes, nil
}
fields := make(map[string]interface{})
err := json.Unmarshal([]byte(attributes["logger:context"]), &fields)
if err != nil {
m.logger.Warn("can not json unmarshal logger context fields during message decoding")
return ctx, attributes, nil
}
ctx = AppendGlobalContextFields(ctx, fields)
delete(attributes, MessageAttributeLoggerContext)
return ctx, attributes, nil
}