Using profiler labels
Goroutines are functions or methods that run concurrently with other functions or methods. To create a goroutine, use the
go keyword followed by a function invocation (for example,
go func(p string, rid int64)). But using lots of goroutines makes a program harder to debug. To differentiate between goroutines, you can label goroutines with custom data.
Since Go 1.9, you can record additional information to provide more context about the execution path. You can record any set of labels as a part of the profiling data and use these labels later to examine the profiler output.
For example, you have a queue handler that processes events created somewhere. The handler can set labels to identify where these events were created.
During debugging and core dump analysis, the context information might be helpful. For example, you can use this information to find a particular goroutine more easily.
runtime/pprof package has several new functions that you can use to add labels. The most popular is the
Do function. The
Do function takes context, adds labels to this context, and passes new context to the f function.
Do function writes labels only for the current goroutine. If you create new goroutines in the f function, you can pass the context as an argument.
Viewing labels in IntelliJ IDEA
For illustrative purposes, copy the following code example from GitHub.
Put a breakpoint where the
println("ok") is called. To put the breakpoint, click the gutter at line 21. Run the debug for the
main function. To start debugging, click the Run icon () in the gutter near the
main function and select Debug <run_debug_configuration_name>. From the Goroutines list, observe available goroutines.
Press Ctrl+F2 to stop debugging. Delete the
f(ctx) call and uncomment the
Do function. Rerun the debugging process by pressing Ctrl+Shift+D. Explore the Goroutines list. Goroutine names include the following information:
/api/profile, userId: <some number>. You can use this information to find a particular goroutine during debugging or core dump analysis.