10

Is there any way I can check if the Go program is compiled with -race enabled at runtime (for e.g. logging/informational purposes)?

I checked the documentation, as well as the obvious locations (runtime/*), but I can't find anything.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146

1 Answers1

15

Since Go 1.18 there's debug.ReadBuildInfo(), which provides this; for example:

func race() {
    b, ok := debug.ReadBuildInfo()
    if !ok {
        fmt.Println("could not read build info")
        return
    }

    for _, s := range b.Settings {
        if s.Key == "-race" {
            fmt.Println("-race=" + s.Value)
            return
        }
    }
    fmt.Println("-race=false")
}

Which will print -race=true or -race=false.

In most cases, simply using the debug.BuildInfo.String() method is probably the easiest, as it prints out other useful stuff as well.

Since this is available since Go 1.18, which is comparatively new at the time of writing, you may want to consider putting a // +build go.18 build tag and provide a shim for older Go versions.


Older pre-Go 1.18 answer, kept for posterity.

As far as I can find there is no simple check for this, but when -race is enabled the race build tag is set, so you can take advantage of that.

I made a new directory israce, and put two files there:

israce/race.go:

// +build race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = true

israce/norace.go:

// +build !race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = false

Due to the build tag only one of the two files will get compiled.

This is also how the Go standard library does it (race.go, norace.go), but since that's an internal package it can't be imported outside of the Go source base.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146