As of Go 1.21, the Go standard library includes log/slog, a structured logging package. This is now the recommended way to perform structured logging in Go applications.
For Google Cloud (App Engine, Cloud Run, Cloud Functions), writing structured JSON logs to stdout/stderr is the recommended approach. slog with JSONHandler supports this natively.
- Structured Logging with slog (Official Go Blog)
- log/slog documentation
- Resources for slog (Community Wiki)
- Structured logging in Google Cloud
Instead of using this package, you can use slog directly. To make slog compatible with Google Cloud Logging's expectations (e.g., using severity instead of level), you can configure the handler like this:
import (
"log/slog"
"os"
)
func init() {
// Configure slog to use JSON handler and map LevelKey to "severity"
opts := &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
// Google Cloud Logging uses "severity" instead of "level"
if a.Key == slog.LevelKey {
return slog.Attr{Key: "severity", Value: a.Value}
}
return a
},
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
slog.SetDefault(logger)
}
func handle(w http.ResponseWriter, r *http.Request) {
// Use slog.Info, slog.Error, etc.
slog.Info("handling request",
"method", r.Method,
"path", r.URL.Path,
"query", r.URL.RawQuery,
)
}Usage is simple:
import (
"github.com/arran4/gaelogger"
"net/http"
)
func init() {
http.HandleFunc("/", handle)
}
func handle(writer http.ResponseWriter, request *http.Request) {
logger := gaelogger.NewLogger(request)
defer logger.Close()
logger.Infof("%s request: %v %v", request.Method, request.URL.RawPath, request.URL.RawQuery)
}This is a Go library; releases consist of a semantic-version tag and a GitHub Release, not a binary artifact.
Run go test -race ./... and go vet ./... to check changes locally. CI also checks dependency integrity, module tidiness, linting and secret scanning on every pull request.
To publish a release, update VERSION and CHANGELOG.md together in a pull request. After the pull request is merged into master, the CI workflow verifies the merge commit before publishing the corresponding v-prefixed release. Regular commits that do not change VERSION do not create new releases. Releases are not published when required checks fail.