Advanced Guide
Using pprof
in GoFr Applications
In GoFr applications, pprof
profiling is automatically enabled. The profiling endpoints are served on the METRICS_PORT
, which defaults to 2121
if not specified.
This guide explains how to enable and use pprof
in GoFr applications.
Enabling pprof
in GoFr
Prerequisites
Ensure the METRICS_PORT
is set (default is 2121
):
METRICS_PORT=2121
GoFr automatically registers the following pprof
routes:
/debug/pprof/cmdline
/debug/pprof/profile
/debug/pprof/symbol
/debug/pprof/trace
/debug/pprof/
(index)
Accessing pprof
Endpoints
Once pprof
is enabled, you can access the profiling endpoints at http://localhost:<METRICS_PORT>/debug/pprof/
. For example, if METRICS_PORT
is 2121
, the endpoints will be available at:
http://localhost:2121/debug/pprof/
Available Endpoints
/debug/pprof/cmdline
:- Returns the command-line arguments of the running application.
/debug/pprof/profile
:- Generates a CPU profile for the application.
/debug/pprof/symbol
:- Resolves program counters into function names.
/debug/pprof/trace
:- Captures an execution trace of the application.
/debug/pprof/
(index):- Provides an index page with links to all available profiling endpoints, including memory, goroutine, and blocking profiles.
Collecting Profiling Data
1. CPU Profiling
To collect a CPU profile:
curl -o cpu.pprof http://localhost:2121/debug/pprof/profile
2. Memory Profiling
To collect a memory profile:
curl -o mem.pprof http://localhost:2121/debug/pprof/heap
3. Goroutine Profiling
To collect information about running goroutines:
curl -o goroutine.pprof http://localhost:2121/debug/pprof/goroutine
4. Execution Trace
To collect an execution trace:
curl -o trace.out http://localhost:2121/debug/pprof/trace
Analyzing Profiling Data
1. Using go tool pprof
To analyze CPU, memory, or goroutine profiles:
go tool pprof <profile_file>
top
Shows the functions consuming the most resources (e.g., CPU or memory).
go tool pprof cpu.pprof
(pprof) top
list
Displays the source code of a specific function, along with resource usage.
(pprof) list <function_name>
Example:
(pprof) list main.myFunction
web
Generates a visual representation of the profile in your browser. This requires Graphviz to be installed.
(pprof) web
2. Using go tool trace
To analyze execution traces:
go tool trace trace.out
Example Workflow
Set Environment Variables:
METRICS_PORT=2121
Run Your GoFr Application:
go run main.go
Collect Profiling Data:
- Collect a CPU profile:
curl -o cpu.pprof http://localhost:2121/debug/pprof/profile
- Collect a memory profile:
curl -o mem.pprof http://localhost:2121/debug/pprof/heap
- Collect a CPU profile:
Analyze the Data:
- Analyze the CPU profile:
go tool pprof cpu.pprof (pprof) top (pprof) list main.myFunction (pprof) web
- Analyze the memory profile:
go tool pprof mem.pprof (pprof) top (pprof) list main.myFunction (pprof) web
- Analyze the CPU profile: