dlv 是什么
dlv(Delve) 是一个非常流行的 Go 调试工具,包括设置断点、单步执行代码、检查变量、分析跟踪堆栈信息等功能。
安装
- 首先确保安装了 Cli 开发者工具(Command line developer tools):
xcode-select --install- 如果你没有开启开发者模式,每次调试的时候都会询问你授权;开启后每次会话仅授权一次:
sudo /usr/sbin/DevToolsSecurity -enable- 可能同时需要添加用户组:
sudo dscl . append /Groups/_developer GroupMembership $(whoami)Mac
brew install delve通过源码安装
go install github.com/go-delve/delve/cmd/dlv@latest快速开始:使用 dlv 进行调试
github.com/me/foo
├── cmd
│ └── foo
│ └── main.go
└── pkg
└── baz
├── bar.go
└── bar_test.go调试普通函数
dlv debug github.com/me/foo/cmd/fooType 'help' for list of commands.
(dlv) break main.main
Breakpoint 1 set at 0x49ecf3 for main.main() ./test.go:5
(dlv) continue
> main.main() ./test.go:5 (hits goroutine(1):1 total:1) (PC: 0x49ecf3)
1: package main
2:
3: import "fmt"
4:
=> 5: func main() {
6: fmt.Println("delve test")
7: }
(dlv) 调试测试函数
dlv test github.com/me/foo/pkg/bazType 'help' for list of commands.
(dlv) funcs test.Test*
/home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi
(dlv) break TestHi
Breakpoint 1 set at 0x536513 for /home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi() ./test_test.go:5
(dlv) continue
> /home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi() ./bar_test.go:5 (hits goroutine(5):1 total:1) (PC: 0x536513)
1: package baz
2:
3: import "testing"
4:
=> 5: func TestHi(t *testing.T) {
6: t.Fatal("implement me!")
7: }
(dlv) 调试 Web API Server
- 以无头(守护进程)启动 debug server:
dlv debug --headless --listen=:8081 main.go看到下面的信息表明启动成功:
API server listening at: [::]:8081
2024-06-09T13:10:28+08:00 warning layer=rpc Listening for remote connections (connections are not authenticated nor encrypted)
debugserver-@(#)PROGRAM:LLDB PROJECT:lldb-1400.0.38.17
for x86_64.
Got a connection, launched process /xxx/__debug_bin1863605193 (pid = 77532).- 连接 debug server 进行调试
dlv connect :8081如何使用
$ dlv -h
Usage:
dlv [command]
Available Commands:
attach Attach to running process and begin debugging.
connect Connect to a headless debug server with a terminal client.
core Examine a core dump.
dap Starts a headless TCP server communicating via Debug Adaptor Protocol (DAP).
debug Compile and begin debugging main package in current directory, or the package specified.
exec Execute a precompiled binary, and begin a debug session.
help Help about any command
run Deprecated command. Use 'debug' instead.
test Compile test binary and begin debugging program.
trace Compile and begin tracing program.
version Prints version.基本用法
- 启动调试会话
dlv debug main.go- 设置断点
# 1)第一种方式
(dlv) break main.main
# 2)或者指定行数(b 等价于 break)
(dlv) b main.go:10- 运行程序
(dlv) continue
# 等价于
(dlv) c- 单步执行
(dlv) next
# 等价于
(dlv) n- 查看变量
(dlv) print myVar
# 等价于
(dlv) p myVar- 查看堆栈信息
(dlv) stack- 设置条件断点
(dlv) break main.go:10 if x == 5- 显示当前代码位置
(dlv) list
# 等价于
(dlv) l