DEV Community

Pranava S Balugari
Pranava S Balugari

Posted on • Edited on

2 1

Go - debug using runtime & log

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
}

Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 


Enter fullscreen mode Exit fullscreen mode

Conclusion:

I will appreciate the constructive feedback about the article. Please share ways to debug go code from your experience.

Thank you :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay