-
Notifications
You must be signed in to change notification settings - Fork 4
/
localjoblogger.go
108 lines (83 loc) · 1.9 KB
/
localjoblogger.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
104
105
106
107
108
package lib
import (
"encoding/json"
"fmt"
"os"
"strings"
"sync"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type LocalMutLogger struct {
sync.Mutex
taskId string
logger *zap.Logger
}
var dbgtl = os.Getenv("DEBUG_TASK_LOGGER") == "true"
func (m *LocalMutLogger) add(p []byte) error {
if dbgtl {
m.logger.Debug("add called", zap.String("taskId", m.taskId))
}
defer m.Unlock()
m.Lock()
var data map[string]any
err := json.Unmarshal(p, &data)
if err != nil {
return fmt.Errorf("failed to unmarshal json: %w", err)
}
// For us, this is just a print
var output strings.Builder
// Get the level
level, ok := data["level"].(string)
if !ok {
level = fmt.Sprint(data["level"])
}
// Get the message
message, ok := data["msg"].(string)
if !ok {
message = fmt.Sprint(data["msg"])
}
output.Write([]byte(fmt.Sprintf("%s: %s", level, message)))
// Write fields
for k, v := range data {
if k == "level" || k == "msg" {
continue
}
switch v := v.(type) {
case float64:
output.Write([]byte(fmt.Sprintf(", %s=%f", k, v)))
case time.Duration:
output.Write([]byte(fmt.Sprintf(", %s=%s", k, v.String())))
default:
output.Write([]byte(fmt.Sprintf(", %s=%s", k, v)))
}
}
fmt.Println(output.String())
return nil
}
func (m *LocalMutLogger) Write(p []byte) (n int, err error) {
if dbgtl {
m.logger.Debug("Write called", zap.String("taskId", m.taskId))
}
err = m.add(p)
if err != nil {
m.logger.Error("[dwWriter] Failed to add to buffer", zap.Error(err), zap.String("taskId", m.taskId))
}
return len(p), err
}
func (m *LocalMutLogger) Sync() error {
return nil
}
func NewLocalTaskLogger(taskId string, l *zap.Logger) (*zap.Logger, *LocalMutLogger) {
ml := &LocalMutLogger{
taskId: taskId,
logger: l,
}
logger := zap.New(zapcore.NewCore(
zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
ml,
zapcore.DebugLevel,
))
return logger, ml
}