diff --git a/pkg/bg/bg.go b/pkg/bg/bg.go index 707236839e..3fd6a74fc3 100644 --- a/pkg/bg/bg.go +++ b/pkg/bg/bg.go @@ -39,37 +39,42 @@ func Work(ctx context.Context, f func(context.Context) error, opts ...Opt) { defer func() { if r := recover(); r != nil { err := fmt.Errorf("recovered from PANIC in background task: %v", r) - logError(err, cfg) + logError(err, cfg, true) } }() if err := f(ctx); err != nil { - logError(err, cfg) + logError(err, cfg, false) } }() } -func logError(err error, cfg config) { +func logError(err error, cfg config, isPanic bool) { if err == nil { return } + evt := cfg.logger.Error().Err(err) + // print stack trace when a panic occurs - buf := make([]byte, 1024) - for { - n := runtime.Stack(buf, false) - if n < len(buf) { - buf = buf[:n] - break + if isPanic { + buf := make([]byte, 1024) + for { + n := runtime.Stack(buf, false) + if n < len(buf) { + buf = buf[:n] + break + } + buf = make([]byte, 2*len(buf)) } - buf = make([]byte, 2*len(buf)) + + evt.Bytes("stack_trace", buf) } - stack := string(buf) name := cfg.name if name == "" { name = "unknown" } - cfg.logger.Error().Err(err).Str("worker.name", name).Interface("stack", stack).Msgf("Background task failed") + evt.Str("worker.name", name).Msg("Background task failed") }