在Linux环境下调试Golang程序有多种方法,下面介绍几种常用的调试工具和技术。
Delve是Go语言专用的调试器,功能强大且易于使用。
go install github.com/go-delve/delve/cmd/dlv@latest
# 启动调试
dlv debug main.go
# 常用命令
b main.main # 设置断点
c # 继续执行
n # 单步执行(不进入函数)
s # 单步执行(进入函数)
p variable # 打印变量值
bt # 查看调用栈
q # 退出调试
虽然不如Delve专业,但GDB也可以用于Go程序调试。
# 编译时需要禁用优化和内联
go build -gcflags="all=-N -l" main.go
# 启动GDB
gdb ./main
对于简单问题,可以使用标准库的log包:
import "log"
func main() {
log.Println("程序启动")
// ...
log.Printf("变量值: %v", someVar)
}
import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 你的程序代码
}
然后可以使用go tool pprof分析:
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/profile
如果你使用VSCode,可以安装Go插件并配置launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${fileDirname}",
"env": {},
"args": []
}
]
}
Go提供了执行跟踪工具:
import (
"os"
"runtime/trace"
)
func main() {
f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()
// 你的程序代码
}
分析trace:
go tool trace trace.out
对于goroutine相关的问题,可以使用:
# 获取所有goroutine的堆栈
kill -SIGQUIT <pid>
# 或者在代码中
import "runtime/debug"
debug.PrintStack()
选择哪种调试方法取决于你的具体需求,简单问题可以用日志,复杂问题推荐使用Delve,性能问题使用pprof,并发问题使用trace或goroutine堆栈分析。