delve安装及使用

发布时间 2023-06-17 18:27:22作者: luo-out
  • 安装

  Clone the git repository and build:$ git clone https://github.com/go-delve/delve

$ cd delve
$ go install github.com/go-delve/delve/cmd/dlv

  Alternatively, on Go version 1.16 or later:

# Install the latest release:
$ go install github.com/go-delve/delve/cmd/dlv@latest

# Install at tree head:
$ go install github.com/go-delve/delve/cmd/dlv@master

# Install at a specific version or pseudo-version:
$ go install github.com/go-delve/delve/cmd/dlv@v1.7.3
$ go install github.com/go-delve/delve/cmd/dlv@v1.7.4-0.20211208103735-2f13672765fe

  macOS considerations

On macOS make sure you also install the command line developer tools:

$ xcode-select --install
If you didn't enable Developer Mode using Xcode you will be asked to authorize the debugger every time you use it. To enable Developer Mode and only have to authorize once per session use:

sudo /usr/sbin/DevToolsSecurity -enable
You might also need to add your user to the developer group:

sudo dscl . append /Groups/_developer GroupMembership $(whoami)

  测试是否安装成功

dlv help
或者
dlv version 
  • 注意  

  如果安装没有报错,但是进行验证时提示:

dlv:command not found

  设置下软链接,这样可以全局使用dlv命令

ln -s $GOPATH/dlv /usr/bin/dlv
注:需配置好go环境
  • dlv启动

  本人经验有限,以下仅个人理解,有什么不对的地方欢迎指出

  dlv有三种调试方法:

    1. 依附正在运行的进程
    2. 编译一个关闭内联优化、生产调试符号的程序包
    3. debug模式
  • 方法一:

    依附进程

dlv attach <Pid> --headless --api-version=2 --listen=:<port>

    Pid可通过ps命令查找

ps aux |grep xxx

    port是dlv开放的调试端口 示例:2345

  • 方法二:

go build -gcflags "all=-N -l" [output] [project]

    output:编译后的包存放的地址及包的名字 示例:-o /opt/bin/test

    project:需要编译的工程地址 示例: ./

dlv --listen=:<port> --headless=true --api-version=2 --accept-multiclient exec <path>

    path:编译好的包地址 示例:./test

  • 方法三:

dlv debug --headless --listen=:<port> --api-version=2 --accept-multiclient
  • 调试

    可通过命令行调试或者使用goland、vscode等工具调试

    这里介绍如何使用命令行和goland进行远程连接调试

  •     命令行
dlv connect <addr>

    addr:远程地址 示例:192.168.0.156:2345

    连接上后利用命令进行调试

  •     goland

    点击工具栏 Run >> edit Configurations

 

                 

     点 + 号新增一个Go Remote 配置远程IP及dlv开放的调试端口,勾选关闭远程调试即kill dlv

     配置好后,点击右上角debug按钮既可进行断点远程调试

    注:不要从main方法旁进行debug