-
Notifications
You must be signed in to change notification settings - Fork 383
/
logutil.go
226 lines (204 loc) · 5.84 KB
/
logutil.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package logutil
import (
"bufio"
"encoding/json"
"fmt"
"io"
"strings"
"sync"
ipfs_log "github.com/ipfs/go-log/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"moul.io/u"
"moul.io/zapfilter"
)
const (
consoleEncoding = "console"
jsonEncoding = "json"
)
func NewLogger(filters string, format string, logFile string) (*zap.Logger, func(), error) {
if filters == "" {
cleanup := func() {}
return zap.NewNop(), cleanup, nil
}
// configure zap
var config zap.Config
switch logFile {
case "":
config = zap.NewDevelopmentConfig()
case "stdout", "stderr":
config = zap.NewDevelopmentConfig()
config.OutputPaths = []string{logFile}
default:
config = zap.NewProductionConfig()
config.OutputPaths = []string{logFile}
}
config.Level.SetLevel(zapcore.DebugLevel)
stableWidthNameEncoder := func(loggerName string, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("%-18s", loggerName))
}
stableWidthCapitalLevelEncoder := func(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("%-5s", l.CapitalString()))
}
const (
Black uint8 = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
White
)
stableWidthCapitalColorLevelEncoder := func(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
switch l {
case zapcore.DebugLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Magenta, "DEBUG"))
case zapcore.InfoLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Blue, "INFO "))
case zapcore.WarnLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Yellow, "WARN "))
case zapcore.ErrorLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Red, "ERROR"))
case zapcore.DPanicLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Red, "DPANIC"))
case zapcore.PanicLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Red, "PANIC"))
case zapcore.FatalLevel:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Red, "FATAL"))
default:
enc.AppendString(fmt.Sprintf("\x1b[%dm%s\x1b[0m", Red, l.CapitalString()))
}
}
switch strings.ToLower(format) {
case "":
// noop
case "json":
config.Encoding = jsonEncoding
case "light-json":
config.Encoding = jsonEncoding
config.EncoderConfig.TimeKey = ""
config.EncoderConfig.EncodeLevel = stableWidthCapitalLevelEncoder
config.DisableStacktrace = true
case "light-console":
config.Encoding = consoleEncoding
config.EncoderConfig.TimeKey = ""
config.EncoderConfig.EncodeLevel = stableWidthCapitalLevelEncoder
config.DisableStacktrace = true
config.EncoderConfig.EncodeName = stableWidthNameEncoder
case "light-color":
config.Encoding = consoleEncoding
config.EncoderConfig.TimeKey = ""
config.EncoderConfig.EncodeLevel = stableWidthCapitalColorLevelEncoder
config.DisableStacktrace = true
config.EncoderConfig.EncodeName = stableWidthNameEncoder
case "console":
config.Encoding = consoleEncoding
config.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
config.EncoderConfig.EncodeLevel = stableWidthCapitalLevelEncoder
config.DisableStacktrace = true
config.EncoderConfig.EncodeName = stableWidthNameEncoder
case "color":
config.Encoding = consoleEncoding
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
config.EncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
config.EncoderConfig.EncodeLevel = stableWidthCapitalColorLevelEncoder
config.DisableStacktrace = true
config.EncoderConfig.EncodeName = stableWidthNameEncoder
default:
return nil, nil, fmt.Errorf("unknown log format: %q", format)
}
base, err := config.Build()
if err != nil {
return nil, nil, err
}
return DecorateLogger(base, filters)
}
func DecorateLogger(base *zap.Logger, filters string) (*zap.Logger, func(), error) {
filter, err := zapfilter.ParseRules(filters)
if err != nil {
return nil, nil, err
}
logger := zap.New(zapfilter.NewFilteringCore(base.Core(), filter))
zap.ReplaceGlobals(logger.Named("other"))
cleanup := func() {
_ = logger.Sync()
}
// IPFS/libp2p logging
{
ipfsLogger := logger.Named("ipfs")
if zapfilter.CheckAnyLevel(ipfsLogger) {
proxyCleanup := setupIPFSLogProxy(ipfsLogger)
cleanup = u.CombineFuncs(proxyCleanup, cleanup)
}
}
return logger.Named("bty"), cleanup, nil
}
func setupIPFSLogProxy(logger *zap.Logger) func() {
// FIXME: write a better bridge for IPFS logger.
// depends on https://github.com/ipfs/go-log/issues/102
ipfs_log.SetupLogging(ipfs_log.Config{
Stderr: false,
Stdout: false,
})
ipfs_log.SetAllLoggers(ipfs_log.LevelDebug)
pr := ipfs_log.NewPipeReader()
r := bufio.NewReader(pr)
var mutex sync.Mutex
go func() {
for {
line, err := r.ReadString('\n')
switch err {
case io.EOF:
return
case nil:
cpy := make([]byte, len(line))
copy(cpy, line)
mutex.Lock()
go func(line []byte) {
defer mutex.Unlock()
var entry struct {
Level string `json:"level"`
Timestamp string `json:"ts"`
LoggerName string `json:"logger"`
Message string `json:"msg"`
}
err = json.Unmarshal(line, &entry)
if err != nil {
logger.Debug(string(line))
return
}
// set logger name
thisLogger := logger
if entry.LoggerName != "" {
thisLogger = thisLogger.Named(entry.LoggerName)
}
// FIXME: parse entry.Timestamp
// escape message (sometimes they contains utf-8 chars that break the terminal)
msg := fmt.Sprintf("%q", entry.Message)
msg = msg[1 : len(msg)-1]
switch entry.Level {
case "debug":
thisLogger.Debug(msg)
case "info":
thisLogger.Info(msg)
case "warn":
thisLogger.Warn(msg)
case "error":
thisLogger.Error(msg)
case "dpanic":
thisLogger.DPanic(msg)
case "panic":
thisLogger.Panic(msg)
case "fatal":
thisLogger.Fatal(msg)
}
}(cpy)
}
}
}()
cleanup := func() {
_ = pr.Close()
}
return cleanup
}