internal/profiler/profiler.go (30 lines of code) (raw):
// Package profiler provides functionality for integrating with Google Cloud Profiler.
// It offers a simple interface to initialize and configure profiling for Go applications,
// with environment variable control to enable/disable profiling. The package supports
// CPU, heap, and mutex profiling through the Google Cloud Profiler service, allowing
// performance monitoring in production environments.
package profiler
import (
"log/slog"
"os"
"cloud.google.com/go/profiler"
"google.golang.org/api/option"
)
type Profiler struct {
start func(cfg profiler.Config, options ...option.ClientOption) error
getenv func(string) string
}
func NewProfiler() Profiler {
return Profiler{
start: profiler.Start,
getenv: os.Getenv,
}
}
func (p *Profiler) Init(serviceName, version string) {
if p.getenv("GOOGLE_CLOUD_PROFILER_ENABLED") == "" {
return
}
err := p.start(profiler.Config{
Service: serviceName,
ServiceVersion: version,
MutexProfiling: true,
})
if err != nil {
slog.Error("could not initialize profiler", "service", serviceName, "version", version, "err", err)
}
}