Skip to content

Debug in Go

homepage-banner

Debugging is an essential part of software development. It involves identifying and fixing errors or bugs in the code. In Golang, debugging is made easier with the help of built-in tools and third-party libraries. In this blog post, we will discuss some of the best practices for debugging in Golang.

One of the simplest ways to debug a Golang program is to use print statements. You can use the fmt.Println() function to print the values of variables, function calls, and other debugging information. This method is useful when you want to quickly check the values of variables at different points in your code.

  1. printf, which allows you to format the numbers, variables, and strings;
  2. print, which only prints the string passed as an argument; and
  3. println, which does the same thing as Print, then adds a new line character (\n) at the end of the string passed to it.
  4. log.Print, which prints the string passed as an argument to the standard output stream.

third-party logging frameworks

  • https://github.com/golang/glog
  • https://github.com/Sirupsen/logrus

gdb

https://go.dev/doc/gdb

When you compile and link your Go programs with the gc toolchain in Linux, macOS, FreeBSD or NetBSD, the resulting binaries contain DWARFv4 debugging information that recent versions (≥7.5) of the GDB debugger can use to inspect a live process or a core dump.

```bash
go build -gcflags=all="-N -l"
```

Delve

https://github.com/go-delve/delve

Delve is a popular debugger for Golang that provides a more user-friendly interface than GDB. It offers similar features like setting breakpoints, inspecting variables, and stepping through code. Additionally, Delve can also be used to debug remote programs running on a different machine or container. To use Delve, you need to install it using the go get command. You can then start Delve by running the dlv command and attaching it to your program.

```bash
go get -u github.com/go-delve/delve/cmd/dlv
dlv debug github.com/me/foo/cmd/foo
```
Leave a message