-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
285 lines (231 loc) · 7.11 KB
/
config.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package app
import (
"errors"
"flag"
"os"
"path/filepath"
"reflect"
"time"
"github.com/TheZeroSlave/zapsentry"
"github.com/getsentry/sentry-go"
"github.com/grongor/panicwatch"
"github.com/mitchellh/mapstructure"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/yaml.v3"
)
type ConfigValidator interface {
Validate() error
}
type genericConfig struct {
App struct {
Logger struct {
Colors bool
Debug bool
Json bool
Sentry struct {
Dsn string
Environment string
}
}
LocalTime bool
Panicwatch bool
}
logger *zap.SugaredLogger
}
func (c *genericConfig) Load(
extensions []Extension,
zapConfig func(*zap.Config),
sentryClientOptions func(*sentry.ClientOptions),
panicwatchConfig func(*panicwatch.Config, *zap.SugaredLogger),
) {
configBytes, err := c.readConfigFile()
if err != nil {
panic("failed to read config file: " + err.Error())
}
configMap := make(map[string]interface{})
err = yaml.Unmarshal(configBytes, &configMap)
if err != nil {
panic("failed to unmarshal YAML config file: " + err.Error())
}
decoderConfig := &mapstructure.DecoderConfig{
Result: c,
DecodeHook: func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if t != reflect.TypeOf(time.Second) {
return data, nil
}
if f.Kind() != reflect.String {
return nil, errors.New("duration must be a string, eg: \"10s\"")
}
return time.ParseDuration(data.(string))
},
}
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
panic("failed to create mapstructure.Decoder: " + err.Error())
}
if err = decoder.Decode(configMap); err != nil {
panic("failed to decode config into the config struct: " + err.Error())
}
if !c.App.LocalTime {
time.Local = time.UTC
}
c.setupLogger(zapConfig, sentryClientOptions)
if c.App.Panicwatch {
c.startPanicwatch(panicwatchConfig)
}
for _, extension := range extensions {
err = extension.Initialize(
func(extensionConfig interface{}) {
if extensionConfig == nil {
c.logger.Panic("app extension config is nil; don't call configLoader if you don't use any config")
}
decoderConfig.Result = extensionConfig
decoder, err = mapstructure.NewDecoder(decoderConfig)
if err != nil {
c.logger.Fatalw("failed to create mapstructure.Decoder for app extension", zap.Error(err))
}
if err = decoder.Decode(configMap); err != nil {
c.logger.Fatalw("failed to unmarshal app extension config", zap.Error(err))
}
if extensionConfig, ok := extensionConfig.(ConfigValidator); ok {
if err = extensionConfig.Validate(); err != nil {
errs := multierr.Errors(err)
if len(errs) > 1 {
c.logger.Fatalw("app extension config validation failed", "errors", errs)
}
c.logger.Fatalw("app extension config validation failed", zap.Error(err))
}
}
},
c.logger,
)
if err != nil {
c.logger.Fatalw("failed to initialize app extension", zap.Error(err))
}
}
}
func (c *genericConfig) readConfigFile() ([]byte, error) {
configFile := flag.String("config", "", "path to a YAML config file")
flag.Parse()
if *configFile == "" {
*configFile = "config.yaml"
}
bytes, err := os.ReadFile(*configFile)
if err != nil && !filepath.IsAbs(*configFile) {
var executablePath string
executablePath, err = os.Executable()
if err != nil {
panic("failed to determine the executable path: " + err.Error())
}
bytes, err = os.ReadFile(filepath.Join(filepath.Dir(executablePath), *configFile))
}
return bytes, err
}
func (c *genericConfig) setupLogger(zapConfig func(*zap.Config), sentryConfig func(*sentry.ClientOptions)) {
loggerConfig := zap.NewProductionConfig()
loggerConfig.Sampling = nil
loggerConfig.EncoderConfig.EncodeTime = func(t time.Time, encoder zapcore.PrimitiveArrayEncoder) {
if !c.App.LocalTime && t.Location() != time.UTC {
t = t.UTC()
}
encoder.AppendString(t.Format("2006-01-02T15:04:05.000"))
}
loggerConfig.EncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
loggerConfig.DisableCaller = true
loggerConfig.DisableStacktrace = true
if !c.App.Logger.Json {
loggerConfig.Encoding = "console"
if c.App.Logger.Colors {
loggerConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
loggerConfig.EncoderConfig.EncodeName = func(name string, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString("\x1b[36m" + name + "\x1b[0m")
}
} else {
loggerConfig.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
}
}
if c.App.Logger.Debug {
loggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
}
if zapConfig != nil {
zapConfig(&loggerConfig)
}
logLevel = &loggerConfig.Level
logger, err := loggerConfig.Build()
if err != nil {
panic("failed to create logger: " + err.Error())
}
if c.App.Logger.Sentry.Dsn == "" {
logger.Warn("Sentry DSN is not set; Sentry integration is disabled")
} else {
logger = c.setupSentryLogging(sentryConfig, logger)
}
c.logger = logger.Sugar()
}
func (c *genericConfig) setupSentryLogging(sentryConfig func(*sentry.ClientOptions), logger *zap.Logger) *zap.Logger {
config := zapsentry.Configuration{Level: zapcore.WarnLevel}
options := sentry.ClientOptions{
Dsn: c.App.Logger.Sentry.Dsn,
AttachStacktrace: true,
Environment: c.App.Logger.Sentry.Environment,
Release: Release,
}
filterIntegrations := func(integrations []sentry.Integration) []sentry.Integration {
filtered := make([]sentry.Integration, 0, len(integrations))
for _, integration := range integrations {
if integration.Name() == "ContextifyFrames" {
continue
}
filtered = append(filtered, integration)
}
return filtered
}
if c.App.Panicwatch {
options.Integrations = func(integrations []sentry.Integration) []sentry.Integration {
return append(
filterIntegrations(integrations),
&PanicwatchSentryIntegration{},
&TrimPathSentryIntegration{},
)
}
} else {
options.Integrations = func(integrations []sentry.Integration) []sentry.Integration {
return append(filterIntegrations(integrations), &TrimPathSentryIntegration{})
}
}
if sentryConfig != nil {
sentryConfig(&options)
}
err := sentry.Init(options)
if err != nil {
logger.Fatal("failed to initialize Sentry SDK", zap.Error(err))
}
core, err := zapsentry.NewCore(config, zapsentry.NewSentryClientFromClient(sentry.CurrentHub().Client()))
if err != nil {
logger.Fatal("failed to initialize zapsentry core", zap.Error(err))
}
return zapsentry.AttachCoreToLogger(core, logger)
}
func (c *genericConfig) startPanicwatch(panicwatchConfig func(*panicwatch.Config, *zap.SugaredLogger)) {
logger := c.logger.Named("panicwatch")
config := panicwatch.Config{
OnPanic: func(p panicwatch.Panic) {
logger.Fatalw(p.Message, "panic", p)
},
OnWatcherError: func(err error) {
logger.Fatalw("watcher error", zap.Error(err))
},
OnWatcherDied: func(err error) {
logger.Fatalw("watcher died", zap.Error(err))
},
}
if panicwatchConfig != nil {
panicwatchConfig(&config, c.logger)
}
err := panicwatch.Start(config)
if err != nil {
c.logger.Fatalw("failed to start panicwatch", zap.Error(err))
}
}