Debugging

suggest change

Debugging Go applications requires understanding how the Go runtime executes compiled native binaries. Because Go features its own goroutine scheduler, memory manager, and concurrency model, specialized tools like Delve (dlv), the built-in Race Detector (-race), and runtime diagnostic packages (runtime/debug, runtime/trace) provide deep visibility into application execution.


1. Interactive Debugging with Delve (dlv)

Delve is the standard interactive debugger for Go. Unlike general-purpose debuggers such as GDB or LLDB, Delve is natively aware of Go runtime structures: it can navigate goroutines, inspect channels, print slices and maps, and unwind Go call stacks correctly.

Installation

go install github.com/go-delve/delve/cmd/dlv@latest

Compiling Without Compiler Optimizations

When building a Go binary for debugging, compiler optimizations and function inlining can reorder instructions or optimize away local variables. Disable optimizations and inlining using -gcflags="all=-N -l":

go build -gcflags="all=-N -l" -o app main.go

Starting Delve

# Debug a package in the current directory directly
dlv debug .

# Or debug an already built executable
dlv exec ./app -- --arg1=value

# Or attach to a running process by PID
dlv attach 12345

# Or debug a test function
dlv test -- -test.run TestOrderCalculation

Essential Delve Commands

Command Shortcut Description
break [loc] b Set a breakpoint (e.g. b main.go:34 or b service.(*Order).Process)
continue c Continue program execution until the next breakpoint
next n Step over to the next source line
step s Step into the function call on the current line
stepout so Step out of the current function to the caller
print [expr] p Evaluate and print a variable or expression
locals Print all local variables in the current function frame
args Print function arguments
goroutines List all active goroutines and their current states
goroutine [id] Switch context to a specific goroutine
stack bt Print the stack trace of the active goroutine
condition [bp] [expr] Set a condition on a breakpoint (e.g., cond 1 count > 100)

2. Programmatic Stack Traces with runtime/debug

When diagnosing unexpected conditions or unhandled errors without halting the program, you can capture or print the current goroutine's call stack programmatically using runtime/debug:

package main

import (
	"fmt"
	"runtime/debug"
)

func processPayment(orderID string, amount float64) error {
	if amount <= 0 {
		fmt.Printf("Invalid payment amount: %.2f for order: %s\n", amount, orderID)
		// Print current stack trace to standard error
		debug.PrintStack()
		return fmt.Errorf("invalid amount: %.2f", amount)
	}
	return nil
}

func main() {
	_ = processPayment("ORD-1092", -50.00)
}

You can also capture the stack trace as a byte slice with debug.Stack() to attach to structured log messages or error monitoring services (such as Sentry).


3. Controlling Crash Dumps with GOTRACEBACK

When a Go program panics, the Go runtime prints a stack trace to standard error. By default, only the crashing goroutine's stack is shown. You can control the verbosity using the GOTRACEBACK environment variable:

# Show stack traces for all active goroutines (useful for deadlocks)
export GOTRACEBACK=all
./app

# Show all goroutines including internal runtime routines (GC, scheduler)
export GOTRACEBACK=system
./app

# Generate an OS core dump upon panic for post-mortem analysis
export GOTRACEBACK=crash
./app

4. Detecting Concurrency Bugs with the Race Detector

Data races occur when two or more goroutines access the same memory location concurrently and at least one access is a write. Data races cause elusive, non-deterministic memory corruption.

Go features a built-in race detector based on ThreadSanitizer:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var counter int
	var wg sync.WaitGroup

	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// DATA RACE: Unsynchronized concurrent read/write
			counter++
		}()
	}

	wg.Wait()
	fmt.Println("Counter:", counter)
}

Run tests or builds with the -race flag:

# Run tests with race detection
go test -race ./...

# Run executable with race detection enabled
go run -race main.go

The race detector outputs an exact report pinpointing both the write and read locations along with the goroutine IDs involved:

==================
WARNING: DATA RACE
Read at 0x00c0000a6010 by goroutine 8:
  main.main.func1()
      /path/to/main.go:17 +0x64

Previous write at 0x00c0000a6010 by goroutine 7:
  main.main.func1()
      /path/to/main.go:17 +0x78
==================

5. Execution Tracing (runtime/trace)

While CPU profilers (pprof) show where CPU time is spent, the Execution Tracer records how goroutines interact over time: scheduler latency, channel blocking, mutex contention, and garbage collection sweeps:

package main

import (
	"os"
	"runtime/trace"
)

func main() {
	f, err := os.Create("trace.out")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	if err := trace.Start(f); err != nil {
		panic(err)
	}
	defer trace.Stop()

	// Application logic here...
}

Analyze the generated trace file in an interactive browser view:

go tool trace trace.out

Debugging Best Practices

  1. Always Test with -race in CI: Integrate go test -race ./... into your continuous integration pipeline to catch concurrency defects before deployment.
  2. Compile with -gcflags="all=-N -l" for Debugging: Ensure variables and line mappings are preserved when using Delve.
  3. Use Structured Logging Alongside Debuggers: In distributed or high-throughput production services where attaching an interactive debugger is impractical, emit structured key-value log entries with correlation IDs.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents