Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

Logging

The go build command supports -buildvcs which stamps VCS metadata into the binary so you can read it at runtime with runtime/debug.ReadBuildInfo. This method for getting version data into the logs is not ideal because it requires VCS metadata, such as from the .git directory. This metadata is often not available in container builds. Another options is to use the -ldflags parameter when running go build. To use -ldflags, create placeholder string vars in your code, like this:

var (
    GitSHA = ""
    BuildTime = ""
)

Then we can set them in the logger:


logger = logger.With(slog.String("git_sha", build.GitSHA), slog.String("build_time", build.BuildTime))

At build time, inject the real values with -ldflags:

go build -ldflags "-X my/package/build.GitSHA=$(git rev-parse HEAD) -X my/package/build.BuildTime=(date -u '+%Y-%m-%dT%H:%M:%SZ')"