Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 13, 14:15 UTC
events: Tune logging and context cancellation
Matthew Holt committed
Aug 31, 2022 at 18:48 UTC
3cd7437b3d2aa7e72129f18991a4eb71214febb6
1 file changed
+16
-10
modules/caddyevents/app.go
+16
-10
@@ -202,11 +202,11 @@ func (app *App) On(eventName string, handler Handler) error {
202
// the metadata data. Events are emitted and propagated synchronously. The returned Event
203
// value will have any additional information from the invoked handlers.
204
func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) Event {
205
+ logger := app.logger.With(zap.String("name", eventName))
206
+
207
id, err := uuid.NewRandom()
208
if err != nil {
207
- app.logger.Error("failed generating new event ID",
208
- zap.Error(err),
209
- zap.String("event", eventName))
209
+ logger.Error("failed generating new event ID", zap.Error(err))
210
}
211
212
eventName = strings.ToLower(eventName)
@@ -219,6 +219,10 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
219
data: data,
220
}
221
222
+ logger = logger.With(
223
+ zap.String("id", e.id.String()),
224
+ zap.String("origin", e.origin.CaddyModule().String()))
225
+
226
// add event info to replacer, make sure it's in the context
227
repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
228
if !ok {
@@ -253,12 +257,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
257
return nil, false
258
})
259
256
- app.logger.Debug("event",
257
- zap.String("name", e.name),
258
- zap.String("id", e.id.String()),
259
- zap.String("origin", e.origin.CaddyModule().String()),
260
- zap.Any("data", e.data),
261
- )
260
+ logger.Debug("event", zap.Any("data", e.data))
261
262
// invoke handlers bound to the event by name and also all events; this for loop
263
// iterates twice at most: once for the event name, once for "" (all events)
@@ -272,10 +271,17 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
271
}
272
273
for _, handler := range app.subscriptions[eventName][moduleID] {
274
+ select {
275
+ case <-ctx.Done():
276
+ logger.Error("context canceled; event handling stopped")
277
+ return e
278
+ default:
279
+ }
280
+
281
if err := handler.Handle(ctx, e); err != nil {
282
aborted := errors.Is(err, ErrAborted)
283
278
- app.logger.Error("handler error",
284
+ logger.Error("handler error",
285
zap.Error(err),
286
zap.Bool("aborted", aborted))
287