/
format.go
103 lines (85 loc) · 2.06 KB
/
format.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
package tyber
import (
"context"
"encoding/json"
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Detail struct {
Name string `json:"name"`
Description string `json:"description"`
}
func safeJSONMarshal(v interface{}) string {
bs, err := json.MarshalIndent(v, "", " ")
if err != nil {
return fmt.Sprintf(`"%s"`, err.Error())
}
return string(bs)
}
func JSONDetail(name string, val interface{}) Detail {
return Detail{Name: name, Description: safeJSONMarshal(val)}
}
func WithJSONDetail(name string, val interface{}) StepMutator {
return func(s Step) Step {
s.Details = append(s.Details, JSONDetail(name, val))
return s
}
}
func WithError(err error) StepMutator {
return func(s Step) Step {
s.Details = append(s.Details, Detail{Name: "Error", Description: err.Error()})
return s
}
}
type LogType string
const (
TraceType LogType = "trace"
StepType LogType = "step"
EventType LogType = "event"
SubscribeType LogType = "subcribe"
)
var KnownLogTypes []LogType = []LogType{TraceType, StepType, EventType, SubscribeType}
func (lt LogType) IsKnown() bool {
for _, vlt := range KnownLogTypes {
if lt == vlt {
return true
}
}
return false
}
type StatusType string
const (
Running StatusType = "running"
Succeeded StatusType = "succeeded"
Failed StatusType = "failed"
)
type Trace struct {
TraceID string `json:"traceID"`
}
type Event struct {
Details []Detail `json:"details"`
}
func FormatTraceLogFields(ctx context.Context) []zapcore.Field {
return []zapcore.Field{
zap.String("tyberLogType", string(TraceType)),
zap.Any("trace", Trace{
TraceID: GetTraceIDFromContext(ctx),
}),
}
}
func FormatEventLogFields(ctx context.Context, details []Detail) []zapcore.Field {
return []zapcore.Field{
zap.String("tyberLogType", string(EventType)),
zap.Any("event", Event{
Details: details,
}),
}
}
func ZapFieldsToDetails(fields ...zap.Field) []Detail {
dets := make([]Detail, len(fields))
for i, field := range fields {
dets[i] = Detail{Name: field.Key, Description: field.String}
}
return dets
}