From 3cd7437b3d2aa7e72129f18991a4eb71214febb6 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 31 Aug 2022 18:48:46 -0600 Subject: [PATCH] events: Tune logging and context cancellation --- modules/caddyevents/app.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/modules/caddyevents/app.go b/modules/caddyevents/app.go index 0c05fe58..3ae40e81 100644 --- a/modules/caddyevents/app.go +++ b/modules/caddyevents/app.go @@ -202,11 +202,11 @@ func (app *App) On(eventName string, handler Handler) error { // the metadata data. Events are emitted and propagated synchronously. The returned Event // value will have any additional information from the invoked handlers. func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) Event { + logger := app.logger.With(zap.String("name", eventName)) + id, err := uuid.NewRandom() if err != nil { - app.logger.Error("failed generating new event ID", - zap.Error(err), - zap.String("event", eventName)) + logger.Error("failed generating new event ID", zap.Error(err)) } eventName = strings.ToLower(eventName) @@ -219,6 +219,10 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E data: data, } + logger = logger.With( + zap.String("id", e.id.String()), + zap.String("origin", e.origin.CaddyModule().String())) + // add event info to replacer, make sure it's in the context repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { @@ -253,12 +257,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E return nil, false }) - app.logger.Debug("event", - zap.String("name", e.name), - zap.String("id", e.id.String()), - zap.String("origin", e.origin.CaddyModule().String()), - zap.Any("data", e.data), - ) + logger.Debug("event", zap.Any("data", e.data)) // invoke handlers bound to the event by name and also all events; this for loop // 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 } for _, handler := range app.subscriptions[eventName][moduleID] { + select { + case <-ctx.Done(): + logger.Error("context canceled; event handling stopped") + return e + default: + } + if err := handler.Handle(ctx, e); err != nil { aborted := errors.Is(err, ErrAborted) - app.logger.Error("handler error", + logger.Error("handler error", zap.Error(err), zap.Bool("aborted", aborted))