Skip to content

Commit 6ebfbd2

Browse files
committed
chore!: adopt log/slog, remove go-kit/log
For: #14355 This commit updates Prometheus to adopt stdlib's log/slog package in favor of go-kit/log. As part of converting to use slog, several other related changes are required to get prometheus working, including: - removed unused logging util func `RateLimit()` - forward ported the util/logging/Deduper logging by implementing a small custom slog.Handler that does the deduping before chaining log calls to the underlying real slog.Logger - move some of the json file logging functionality to use prom/common package functionality - refactored some of the new json file logging for scraping - changes to promql.QueryLogger interface to swap out logging methods for relevant slog sugar wrappers - updated lots of tests that used/replicated custom logging functionality, attempting to keep the logical goal of the tests consistent after the transition - added a healthy amount of `if logger == nil { $makeLogger }` type conditional checks amongst various functions where none were provided -- old code that used the go-kit/log.Logger interface had several places where there were nil references when trying to use functions like `With()` to add keyvals on the new *slog.Logger type Signed-off-by: TJ Hoplock <[email protected]>
1 parent 65f6103 commit 6ebfbd2

File tree

162 files changed

+1534
-1691
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

162 files changed

+1534
-1691
lines changed

.golangci.yml

+1-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ linters:
2323
- usestdlibvars
2424
- whitespace
2525
- loggercheck
26+
- sloglint
2627

2728
issues:
2829
max-issues-per-linter: 0
@@ -100,8 +101,6 @@ linters-settings:
100101
- (net/http.ResponseWriter).Write
101102
# No need to check for errors on server's shutdown.
102103
- (*net/http.Server).Shutdown
103-
# Never check for logger errors.
104-
- (github.com/go-kit/log.Logger).Log
105104
# Never check for rollback errors as Rollback() is called when a previous error was detected.
106105
- (github.com/prometheus/prometheus/storage.Appender).Rollback
107106
goimports:

cmd/prometheus/main.go

+146-109
Large diffs are not rendered by default.

cmd/prometheus/main_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ import (
3131
"time"
3232

3333
"github.com/alecthomas/kingpin/v2"
34-
"github.com/go-kit/log"
3534
"github.com/prometheus/client_golang/prometheus"
3635
"github.com/prometheus/common/model"
36+
"github.com/prometheus/common/promslog"
3737
"github.com/stretchr/testify/require"
3838

3939
"github.com/prometheus/prometheus/config"
@@ -295,7 +295,7 @@ func TestTimeMetrics(t *testing.T) {
295295
tmpDir := t.TempDir()
296296

297297
reg := prometheus.NewRegistry()
298-
db, err := openDBWithMetrics(tmpDir, log.NewNopLogger(), reg, nil, nil)
298+
db, err := openDBWithMetrics(tmpDir, promslog.NewNopLogger(), reg, nil, nil)
299299
require.NoError(t, err)
300300
defer func() {
301301
require.NoError(t, db.Close())

cmd/prometheus/query_log_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,7 @@ func readQueryLog(t *testing.T, path string) []queryLogLine {
442442
file, err := os.Open(path)
443443
require.NoError(t, err)
444444
defer file.Close()
445+
445446
scanner := bufio.NewScanner(file)
446447
for scanner.Scan() {
447448
var q queryLogLine

cmd/promtool/backfill.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@ import (
2121
"math"
2222
"time"
2323

24-
"github.com/go-kit/log"
2524
"github.com/oklog/ulid"
2625

26+
"github.com/prometheus/common/promslog"
27+
2728
"github.com/prometheus/prometheus/model/labels"
2829
"github.com/prometheus/prometheus/model/textparse"
2930
"github.com/prometheus/prometheus/tsdb"
@@ -120,7 +121,7 @@ func createBlocks(input []byte, mint, maxt, maxBlockDuration int64, maxSamplesIn
120121
// also need to append samples throughout the whole block range. To allow that, we
121122
// pretend that the block is twice as large here, but only really add sample in the
122123
// original interval later.
123-
w, err := tsdb.NewBlockWriter(log.NewNopLogger(), outputDir, 2*blockDuration)
124+
w, err := tsdb.NewBlockWriter(promslog.NewNopLogger(), outputDir, 2*blockDuration)
124125
if err != nil {
125126
return fmt.Errorf("block writer: %w", err)
126127
}

cmd/promtool/main.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,13 @@ import (
3232
"time"
3333

3434
"github.com/alecthomas/kingpin/v2"
35-
"github.com/go-kit/log"
3635
"github.com/google/pprof/profile"
3736
"github.com/prometheus/client_golang/api"
3837
"github.com/prometheus/client_golang/prometheus"
3938
"github.com/prometheus/client_golang/prometheus/testutil/promlint"
4039
config_util "github.com/prometheus/common/config"
4140
"github.com/prometheus/common/model"
41+
"github.com/prometheus/common/promslog"
4242
"github.com/prometheus/common/version"
4343
"github.com/prometheus/exporter-toolkit/web"
4444
"gopkg.in/yaml.v2"
@@ -575,7 +575,7 @@ func checkFileExists(fn string) error {
575575
func checkConfig(agentMode bool, filename string, checkSyntaxOnly bool) ([]string, error) {
576576
fmt.Println("Checking", filename)
577577

578-
cfg, err := config.LoadFile(filename, agentMode, false, log.NewNopLogger())
578+
cfg, err := config.LoadFile(filename, agentMode, false, promslog.NewNopLogger())
579579
if err != nil {
580580
return nil, err
581581
}
@@ -1182,7 +1182,7 @@ func importRules(url *url.URL, roundTripper http.RoundTripper, start, end, outpu
11821182
return fmt.Errorf("new api client error: %w", err)
11831183
}
11841184

1185-
ruleImporter := newRuleImporter(log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)), cfg, api)
1185+
ruleImporter := newRuleImporter(promslog.New(&promslog.Config{}), cfg, api)
11861186
errs := ruleImporter.loadGroups(ctx, files)
11871187
for _, err := range errs {
11881188
if err != nil {

cmd/promtool/rules.go

+9-9
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ package main
1616
import (
1717
"context"
1818
"fmt"
19+
"log/slog"
1920
"time"
2021

21-
"github.com/go-kit/log"
22-
"github.com/go-kit/log/level"
2322
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
2423
"github.com/prometheus/common/model"
24+
"github.com/prometheus/common/promslog"
2525

2626
"github.com/prometheus/prometheus/model/labels"
2727
"github.com/prometheus/prometheus/model/timestamp"
@@ -38,7 +38,7 @@ type queryRangeAPI interface {
3838
}
3939

4040
type ruleImporter struct {
41-
logger log.Logger
41+
logger *slog.Logger
4242
config ruleImporterConfig
4343

4444
apiClient queryRangeAPI
@@ -57,8 +57,8 @@ type ruleImporterConfig struct {
5757

5858
// newRuleImporter creates a new rule importer that can be used to parse and evaluate recording rule files and create new series
5959
// written to disk in blocks.
60-
func newRuleImporter(logger log.Logger, config ruleImporterConfig, apiClient queryRangeAPI) *ruleImporter {
61-
level.Info(logger).Log("backfiller", "new rule importer", "start", config.start.Format(time.RFC822), "end", config.end.Format(time.RFC822))
60+
func newRuleImporter(logger *slog.Logger, config ruleImporterConfig, apiClient queryRangeAPI) *ruleImporter {
61+
logger.Info("new rule importer", "component", "backfiller", "start", config.start.Format(time.RFC822), "end", config.end.Format(time.RFC822))
6262
return &ruleImporter{
6363
logger: logger,
6464
config: config,
@@ -80,10 +80,10 @@ func (importer *ruleImporter) loadGroups(_ context.Context, filenames []string)
8080
// importAll evaluates all the recording rules and creates new time series and writes them to disk in blocks.
8181
func (importer *ruleImporter) importAll(ctx context.Context) (errs []error) {
8282
for name, group := range importer.groups {
83-
level.Info(importer.logger).Log("backfiller", "processing group", "name", name)
83+
importer.logger.Info("processing group", "component", "backfiller", "name", name)
8484

8585
for i, r := range group.Rules() {
86-
level.Info(importer.logger).Log("backfiller", "processing rule", "id", i, "name", r.Name())
86+
importer.logger.Info("processing rule", "component", "backfiller", "id", i, "name", r.Name())
8787
if err := importer.importRule(ctx, r.Query().String(), r.Name(), r.Labels(), importer.config.start, importer.config.end, int64(importer.config.maxBlockDuration/time.Millisecond), group); err != nil {
8888
errs = append(errs, err)
8989
}
@@ -124,7 +124,7 @@ func (importer *ruleImporter) importRule(ctx context.Context, ruleExpr, ruleName
124124
return fmt.Errorf("query range: %w", err)
125125
}
126126
if warnings != nil {
127-
level.Warn(importer.logger).Log("msg", "Range query returned warnings.", "warnings", warnings)
127+
importer.logger.Warn("Range query returned warnings.", "warnings", warnings)
128128
}
129129

130130
// To prevent races with compaction, a block writer only allows appending samples
@@ -133,7 +133,7 @@ func (importer *ruleImporter) importRule(ctx context.Context, ruleExpr, ruleName
133133
// also need to append samples throughout the whole block range. To allow that, we
134134
// pretend that the block is twice as large here, but only really add sample in the
135135
// original interval later.
136-
w, err := tsdb.NewBlockWriter(log.NewNopLogger(), importer.config.outputDir, 2*blockDuration)
136+
w, err := tsdb.NewBlockWriter(promslog.NewNopLogger(), importer.config.outputDir, 2*blockDuration)
137137
if err != nil {
138138
return fmt.Errorf("new block writer: %w", err)
139139
}

cmd/promtool/rules_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ import (
2121
"testing"
2222
"time"
2323

24-
"github.com/go-kit/log"
2524
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
2625
"github.com/prometheus/common/model"
26+
"github.com/prometheus/common/promslog"
2727
"github.com/stretchr/testify/require"
2828

2929
"github.com/prometheus/prometheus/model/labels"
@@ -161,7 +161,7 @@ func TestBackfillRuleIntegration(t *testing.T) {
161161
}
162162

163163
func newTestRuleImporter(_ context.Context, start time.Time, tmpDir string, testSamples model.Matrix, maxBlockDuration time.Duration) (*ruleImporter, error) {
164-
logger := log.NewNopLogger()
164+
logger := promslog.NewNopLogger()
165165
cfg := ruleImporterConfig{
166166
outputDir: tmpDir,
167167
start: start.Add(-10 * time.Hour),

cmd/promtool/sd.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ import (
2020
"os"
2121
"time"
2222

23-
"github.com/go-kit/log"
2423
"github.com/google/go-cmp/cmp"
2524
"github.com/prometheus/client_golang/prometheus"
25+
"github.com/prometheus/common/promslog"
2626

2727
"github.com/prometheus/prometheus/config"
2828
"github.com/prometheus/prometheus/discovery"
@@ -39,7 +39,7 @@ type sdCheckResult struct {
3939

4040
// CheckSD performs service discovery for the given job name and reports the results.
4141
func CheckSD(sdConfigFiles, sdJobName string, sdTimeout time.Duration, registerer prometheus.Registerer) int {
42-
logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
42+
logger := promslog.New(&promslog.Config{})
4343

4444
cfg, err := config.LoadFile(sdConfigFiles, false, false, logger)
4545
if err != nil {

cmd/promtool/tsdb.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"errors"
2121
"fmt"
2222
"io"
23+
"log/slog"
2324
"os"
2425
"path/filepath"
2526
"runtime"
@@ -32,9 +33,10 @@ import (
3233
"time"
3334

3435
"github.com/alecthomas/units"
35-
"github.com/go-kit/log"
3636
"go.uber.org/atomic"
3737

38+
"github.com/prometheus/common/promslog"
39+
3840
"github.com/prometheus/prometheus/model/labels"
3941
"github.com/prometheus/prometheus/promql/parser"
4042
"github.com/prometheus/prometheus/storage"
@@ -60,15 +62,15 @@ type writeBenchmark struct {
6062
memprof *os.File
6163
blockprof *os.File
6264
mtxprof *os.File
63-
logger log.Logger
65+
logger *slog.Logger
6466
}
6567

6668
func benchmarkWrite(outPath, samplesFile string, numMetrics, numScrapes int) error {
6769
b := &writeBenchmark{
6870
outPath: outPath,
6971
samplesFile: samplesFile,
7072
numMetrics: numMetrics,
71-
logger: log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)),
73+
logger: promslog.New(&promslog.Config{}),
7274
}
7375
if b.outPath == "" {
7476
dir, err := os.MkdirTemp("", "tsdb_bench")
@@ -87,9 +89,7 @@ func benchmarkWrite(outPath, samplesFile string, numMetrics, numScrapes int) err
8789

8890
dir := filepath.Join(b.outPath, "storage")
8991

90-
l := log.With(b.logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
91-
92-
st, err := tsdb.Open(dir, l, nil, &tsdb.Options{
92+
st, err := tsdb.Open(dir, b.logger, nil, &tsdb.Options{
9393
RetentionDuration: int64(15 * 24 * time.Hour / time.Millisecond),
9494
MinBlockDuration: int64(2 * time.Hour / time.Millisecond),
9595
}, tsdb.NewDBStats())

cmd/promtool/unittest.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,13 @@ import (
2626
"strings"
2727
"time"
2828

29-
"github.com/go-kit/log"
3029
"github.com/google/go-cmp/cmp"
3130
"github.com/grafana/regexp"
3231
"github.com/nsf/jsondiff"
3332
"gopkg.in/yaml.v2"
3433

3534
"github.com/prometheus/common/model"
35+
"github.com/prometheus/common/promslog"
3636

3737
"github.com/prometheus/prometheus/model/histogram"
3838
"github.com/prometheus/prometheus/model/labels"
@@ -218,7 +218,7 @@ func (tg *testGroup) test(evalInterval time.Duration, groupOrderMap map[string]i
218218
Appendable: suite.Storage(),
219219
Context: context.Background(),
220220
NotifyFunc: func(ctx context.Context, expr string, alerts ...*rules.Alert) {},
221-
Logger: log.NewNopLogger(),
221+
Logger: promslog.NewNopLogger(),
222222
}
223223
m := rules.NewManager(opts)
224224
groupsMap, ers := m.LoadGroups(time.Duration(tg.Interval), tg.ExternalLabels, tg.ExternalURL, nil, ruleFiles...)

config/config.go

+5-6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package config
1616
import (
1717
"errors"
1818
"fmt"
19+
"log/slog"
1920
"net/url"
2021
"os"
2122
"path/filepath"
@@ -25,8 +26,6 @@ import (
2526
"time"
2627

2728
"github.com/alecthomas/units"
28-
"github.com/go-kit/log"
29-
"github.com/go-kit/log/level"
3029
"github.com/grafana/regexp"
3130
"github.com/prometheus/common/config"
3231
"github.com/prometheus/common/model"
@@ -73,7 +72,7 @@ const (
7372
)
7473

7574
// Load parses the YAML input s into a Config.
76-
func Load(s string, expandExternalLabels bool, logger log.Logger) (*Config, error) {
75+
func Load(s string, expandExternalLabels bool, logger *slog.Logger) (*Config, error) {
7776
cfg := &Config{}
7877
// If the entire config body is empty the UnmarshalYAML method is
7978
// never called. We thus have to set the DefaultConfig at the entry
@@ -98,11 +97,11 @@ func Load(s string, expandExternalLabels bool, logger log.Logger) (*Config, erro
9897
if v := os.Getenv(s); v != "" {
9998
return v
10099
}
101-
level.Warn(logger).Log("msg", "Empty environment variable", "name", s)
100+
logger.Warn("Empty environment variable", "name", s)
102101
return ""
103102
})
104103
if newV != v.Value {
105-
level.Debug(logger).Log("msg", "External label replaced", "label", v.Name, "input", v.Value, "output", newV)
104+
logger.Debug("External label replaced", "label", v.Name, "input", v.Value, "output", newV)
106105
}
107106
// Note newV can be blank. https://github.com/prometheus/prometheus/issues/11024
108107
b.Add(v.Name, newV)
@@ -112,7 +111,7 @@ func Load(s string, expandExternalLabels bool, logger log.Logger) (*Config, erro
112111
}
113112

114113
// LoadFile parses the given YAML file into a Config.
115-
func LoadFile(filename string, agentMode, expandExternalLabels bool, logger log.Logger) (*Config, error) {
114+
func LoadFile(filename string, agentMode, expandExternalLabels bool, logger *slog.Logger) (*Config, error) {
116115
content, err := os.ReadFile(filename)
117116
if err != nil {
118117
return nil, err

0 commit comments

Comments
 (0)