When debugging programs with lots of interconnected functions in different files calling one another, it will be useful to know which file is executing at certain points in the program and the may be line number its emanating from. This can be done by using special functions from the packages runtime or log in go.
package main
import "fmt"
import "runtime"
import "log"
func main() {
// Below where is our debug function
where := func() {
_, file, line, _ := runtime.Caller(1) // Provides debug info
log.Printf("%s:%d \n", file, line)
}
where() // Call your debug function
name := "Pranava"
salary := 1 * 10 // in cents :P
fmt.Printf("%s 's salary : %d \n",name, salary)
where() // Call your debug function
// some more code
costOfLiving := salary * 1000000
fmt.Printf("Cost of living : %d \n", costOfLiving)
where() // Call your debug function
}
Output will look something similar to below...
2020/06/03 19:48:14 /Users/pranavaswaroop/learning/gophercises/main.go:13
Pranava 's salary : 10
2020/06/03 19:48:14 /Users/pranavaswaroop/learning/gophercises/main.go:19
Cost of living : 10000000
2020/06/03 19:48:14 /Users/pranavaswaroop/learning/gophercises/main.go:25
The same can be achieved using log package:
package main
import "fmt"
import "log"
func main() {
// Below where is our debug function
where := log.Print
where() // Call your debug function
name := "Pranava"
salary := 1 * 10 // in cents :P
fmt.Printf("%s 's salary : %d \n",name, salary)
where() // Call your debug function
// some more code
costOfLiving := salary * 1000000
fmt.Printf("Cost of living : %d \n", costOfLiving)
where() // Call your debug function
}
Output:
2020/06/03 19:53:08
Pranava 's salary : 10
2020/06/03 19:53:08
Cost of living : 10000000
2020/06/03 19:53:08
Conclusion:
I will appreciate the constructive feedback about the article. Please share ways to debug go
code from your experience.
Thank you :)
Top comments (0)