How can I see if the GoLand debugger is running in the program?

后端 未结 3 1289
-上瘾入骨i
-上瘾入骨i 2021-01-14 15:52

In C# the executing program can detect if it\'s running in the debugger using:

System.Diagnostics.Debugger.IsAttached

Is there an equivalen

3条回答
  •  悲&欢浪女
    2021-01-14 16:00

    As far as I know, there is no built-in way to do this in the manner you described. But you can do more or less the same using build tags to indicate that the delve debugger is running. You can pass build tags to dlv with the --build-flags argument. This is basically the same technique as I described in How can I check if the race detector is enabled at runtime?

    isdelve/delve.go

    // +build delve
    
    package isdelve
    
    const Enabled = true
    

    isdelve/nodelve.go:

    // +build !delve
    
    package isdelve
    
    const Enabled = false
    

    a.go:

    package main
    
    import (
        "isdelve"
        "fmt"
    )
    
    func main() {
        fmt.Println("delve", isdelve.Enabled)
    }
    

    In Goland, you can enable this under 'Run/Debug Configurations', by adding the following into 'Go tool arguments:'

    -tags=delve
    


    If you are outside of Goland, running go run a.go will report delve false, if you want to run dlv on its own, use dlv debug --build-flags='-tags=delve' a.go; this will report delve true.


    Alternatively, you can use delve's set command to manually set a variable after starting the debugger.

提交回复
热议问题