Member-only story
Logging for Concurrent Go Programs
2 min readNov 30, 2022
Log is an important part for debugging.
Troubleshooting and debugging of a concurrent program is difficult. In Golang, this getting even worse as officially the Goroutine’s id is not exposed for access.
But its kind of well known and spread out that the goroutine id can be obtained using some go runtime stack information. This technique can even be found in the golang source code.
Obtain the Goroutine ID
Have the following function to get the current goroutine id.
func goid() int {
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Sprintf("cannot get goroutine id: %v", err))
}
return id
}
You can then have a helping function to log with the goroutine id
func init() {
log.SetFlags(log.Lmicroseconds)
}
func DebugPrint(format string, args ...interface{}) {
if os.Getenv("DEBUG") == "true" {
v := []interface{}{goid()}
v = append(v, args...)
log.Printf("debug_goroutine:%02d: "+format, v...)
}
}
Set the log time format with microseconds. Create a helper function to log with the current goroutine id.