Skip to content

Commit

Permalink
Fix bg
Browse files Browse the repository at this point in the history
  • Loading branch information
swift1337 committed Jul 18, 2024
1 parent f199256 commit da593ce
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions pkg/bg/bg.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

0 comments on commit da593ce

Please sign in to comment.