Skip to content

Commit d630955

Browse files
Instrument memory profiling (#889)
1 parent bfda7fd commit d630955

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

cmd/exporter/config/config.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ type Config struct {
3535
}
3636

3737
Server struct {
38-
Address string
39-
Path string
40-
Timeout time.Duration
38+
Address string
39+
Path string
40+
Timeout time.Duration
41+
DebugAddress string
4142
}
4243
LoggerOpts struct {
4344
Level string // Maps to slog levels: debug, info, warn, error

cmd/exporter/exporter.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"log/slog"
99
"net/http"
10+
_ "net/http/pprof"
1011
"os"
1112
"os/signal"
1213
"strings"
@@ -95,6 +96,7 @@ func operationalFlags(cfg *config.Config) {
9596
flag.StringVar(&cfg.LoggerOpts.Level, "log.level", "info", "Log level: debug, info, warn, error")
9697
flag.StringVar(&cfg.LoggerOpts.Output, "log.output", "stdout", "Log output stream: stdout, stderr, file")
9798
flag.StringVar(&cfg.LoggerOpts.Type, "log.type", "text", "Log type: json, text")
99+
flag.StringVar(&cfg.Server.DebugAddress, "debug.address", ":6060", "Address for the pprof debug server (e.g. :6060). Disabled when empty.")
98100
}
99101

100102
// setupLogger is a helper method that is responsible for creating a structured logger that is used throughout the application.
@@ -104,8 +106,25 @@ func setupLogger(level string, output string, logtype string) *slog.Logger {
104106
return slog.New(handler)
105107
}
106108

109+
// startDebugServer starts a pprof HTTP server on cfg.Server.DebugAddress.
110+
// It is a no-op when DebugAddress is empty.
111+
func startDebugServer(ctx context.Context, cfg *config.Config, log *slog.Logger) {
112+
if cfg.Server.DebugAddress == "" {
113+
return
114+
}
115+
log.LogAttrs(ctx, slog.LevelInfo, "Starting pprof debug server", slog.String("address", cfg.Server.DebugAddress))
116+
go func() {
117+
// http.DefaultServeMux has pprof routes registered via the blank import.
118+
if err := http.ListenAndServe(cfg.Server.DebugAddress, http.DefaultServeMux); err != nil {
119+
log.LogAttrs(ctx, slog.LevelError, "pprof debug server stopped", slog.String("message", err.Error()))
120+
}
121+
}()
122+
}
123+
107124
// runServer is a helper method that is responsible for starting the metrics server and handling shutdown signals.
108125
func runServer(ctx context.Context, cfg *config.Config, csp provider.Provider, log *slog.Logger) error {
126+
startDebugServer(ctx, cfg, log)
127+
109128
mux := http.NewServeMux()
110129

111130
mux.HandleFunc("/", web.HomePageHandler(cfg.Server.Path)) // landing page

0 commit comments

Comments
 (0)