| 486 | } |
| 487 | |
| 488 | func goroutineProfiling(ctx context.Context, interval time.Duration) { |
| 489 | ticker := time.NewTicker(interval) |
| 490 | defer ticker.Stop() |
| 491 | numGoroutines.Add(1) |
| 492 | defer numGoroutines.Add(-1) |
| 493 | for { |
| 494 | select { |
| 495 | case <-ctx.Done(): |
| 496 | return |
| 497 | case <-ticker.C: |
| 498 | fileName := fmt.Sprintf("goroutine-%s.prof", time.Now().Format(time.RFC3339)) |
| 499 | goroutineProfBuf := bytes.Buffer{} |
| 500 | err := pprof.Lookup("goroutine").WriteTo(&goroutineProfBuf, 1) |
| 501 | if err != nil { |
| 502 | log.Printf("Error writing goroutine profile: %v", err) |
| 503 | return |
| 504 | } |
| 505 | |
| 506 | err = os.WriteFile(fileName, goroutineProfBuf.Bytes(), os.ModePerm) |
| 507 | if err != nil { |
| 508 | log.Printf("Error writing goroutine profile to file: %v", err) |
| 509 | return |
| 510 | } |
| 511 | } |
| 512 | } |
| 513 | } |