pprof_enabled.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //go:build pprof
  2. package main
  3. import (
  4. "flag"
  5. "fmt"
  6. "net/http"
  7. _ "net/http/pprof"
  8. "os"
  9. "runtime"
  10. "time"
  11. )
  12. var (
  13. pprofAddr = flag.String("pprof", "", "Enable pprof debug server on this address (e.g. localhost:6060)")
  14. pprofBlockRate = flag.Int("pprof-block-rate", 0, "Set runtime block profile rate when pprof is enabled (0 disables block profiling)")
  15. pprofMutexFraction = flag.Int("pprof-mutex-fraction", 0, "Set runtime mutex profile fraction when pprof is enabled (0 disables mutex profiling)")
  16. )
  17. func init() {
  18. startPprofServerHook = startPprofServer
  19. }
  20. func startPprofServer() *http.Server {
  21. if *pprofAddr == "" {
  22. return nil
  23. }
  24. if *pprofBlockRate > 0 {
  25. runtime.SetBlockProfileRate(*pprofBlockRate)
  26. }
  27. if *pprofMutexFraction > 0 {
  28. runtime.SetMutexProfileFraction(*pprofMutexFraction)
  29. }
  30. srv := &http.Server{
  31. Addr: *pprofAddr,
  32. Handler: http.DefaultServeMux,
  33. ReadTimeout: 5 * time.Second,
  34. WriteTimeout: 120 * time.Second,
  35. }
  36. go func() {
  37. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  38. fmt.Fprintf(os.Stderr, "pprof server error: %v\n", err)
  39. }
  40. }()
  41. return srv
  42. }