add pprof http server support with a build tag switch

This commit is contained in:
c9s 2024-11-15 17:25:00 +08:00
parent 56fdf0a21f
commit 2e39200214
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 27 additions and 2 deletions

6
pkg/cmd/pprof.go Normal file
View File

@ -0,0 +1,6 @@
//go:build pprof
// +build pprof
package cmd
import _ "net/http/pprof"

View File

@ -7,6 +7,7 @@ import (
"runtime/pprof" "runtime/pprof"
"strings" "strings"
"time" "time"
_ "time/tzdata"
"github.com/heroku/rollrus" "github.com/heroku/rollrus"
"github.com/joho/godotenv" "github.com/joho/godotenv"
@ -20,8 +21,6 @@ import (
"github.com/c9s/bbgo/pkg/bbgo" "github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/util" "github.com/c9s/bbgo/pkg/util"
_ "time/tzdata"
) )
var cpuProfileFile *os.File var cpuProfileFile *os.File
@ -81,6 +80,24 @@ var RootCmd = &cobra.Command{
}() }()
} }
enableProfileServer, err := cmd.Flags().GetBool("enable-profile-server")
if err != nil {
return err
}
if enableProfileServer {
profileServerBind, err := cmd.Flags().GetString("profile-server-bind")
if err != nil {
return err
}
go func() {
if err := http.ListenAndServe(profileServerBind, nil); err != nil {
log.WithError(err).Errorf("profile server error")
}
}()
}
cpuProfile, err := cmd.Flags().GetString("cpu-profile") cpuProfile, err := cmd.Flags().GetString("cpu-profile")
if err != nil { if err != nil {
return err return err
@ -195,6 +212,8 @@ func init() {
RootCmd.PersistentFlags().String("max-api-secret", "", "max api secret") RootCmd.PersistentFlags().String("max-api-secret", "", "max api secret")
RootCmd.PersistentFlags().String("cpu-profile", "", "cpu profile") RootCmd.PersistentFlags().String("cpu-profile", "", "cpu profile")
RootCmd.PersistentFlags().Bool("enable-profile-server", false, "enable profile server binding")
RootCmd.PersistentFlags().String("profile-server-bind", "localhost:6060", "profile server binding")
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))