Golang (GO) pprof in Beego

A great feature of Go’s standard library is its code performance monitoring tools. These packages exist in two places:

net/http/pprof

In fact, net/http/pprof simply exposes runtime profiling data from the runtime/pprof package on an HTTP port.

pprof support in Beego

The Beego framework currently supports pprof, however it is not turned on by default. If you need to test the performance of your application, (for instance by viewing the execution goroutine) such information from Go’s default package “net/http/pprof” already has this feature. Because beego has repackaged the ServHTTP function, you can not open the default feature included in pprof. This resulted in beego supporting pprof internally.

  • First in our beego.Run function, we choose whether or not to automatically load the performance pack according to our configuration variable (in this case, PprofOn):
  • if PprofOn { BeeApp.RegisterController(`/debug/pprof`, &ProfController{}) BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{}) }
  • Designing ProfController
  • package beego import ( "net/http/pprof" ) type ProfController struct { Controller } func (this *ProfController) Get() { switch this.Ctx.Params[":pp"] { default: pprof.Index(this.Ctx.ResponseWriter, this.Ctx.Request) case "": pprof.Index(this.Ctx.ResponseWriter, this.Ctx.Request) case "cmdline": pprof.Cmdline(this.Ctx.ResponseWriter, this.Ctx.Request) case "profile": pprof.Profile(this.Ctx.ResponseWriter, this.Ctx.Request) case "symbol": pprof.Symbol(this.Ctx.ResponseWriter, this.Ctx.Request) } this.Ctx.ResponseWriter.WriteHeader(200) }

Getting started

From the above, we can see that enabling pprof is as simple as setting the PprofOn configuration variable to true:

beego.PprofOn = true

You can then open the following URL in your browser to see the following interface:

Figure 14.7 current system goroutine, heap, thread information

By clicking on a goroutine, we can see a lot of detailed information:

Figure 14.8 shows the current goroutine details

Of course, we can also get more details from the command line:

go tool pprof http://localhost:8080/debug/pprof/profile

This time, the program will begin profiling the application for a period of 30 seconds, during which time it will repeatedly refresh the page in the browser in an attempt to gather CPU usage and performance data.

(pprof) top10

Figure 14.9 shows the execution flow of information

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store