Skip to content

Commit def8ffd

Browse files
authored
logging: switch to using log/slog (#138)
1 parent 4fa9e59 commit def8ffd

24 files changed

+1020
-292
lines changed

.github/actions/terraform-linter/action.yml

+3-2
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,10 @@ runs:
3131
- id: 'setup-go'
3232
uses: 'actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753' # ratchet:actions/setup-go@v4
3333
with:
34-
go-version: '1.20'
34+
go-version: '1.21'
3535

3636
- id: 'run-linter'
3737
shell: 'bash'
3838
working-directory: 'abcxyz-pkg'
39-
run: 'go run ./cmd/terraform-linter ${GITHUB_WORKSPACE}/${{inputs.directory}}'
39+
run: |-
40+
go run ./cmd/terraform-linter ${GITHUB_WORKSPACE}/${{inputs.directory}}

.github/workflows/ci.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,12 @@ jobs:
3030
go_lint:
3131
uses: './.github/workflows/go-lint.yml'
3232
with:
33-
go_version: '1.20'
33+
go_version: '1.21'
3434

3535
go_test:
3636
uses: './.github/workflows/go-test.yml'
3737
with:
38-
go_version: '1.20'
38+
go_version: '1.21'
3939

4040
terraform_lint:
4141
uses: './.github/workflows/terraform-lint.yml'

.github/workflows/go-lint.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ on:
3232
golangci_lint_version:
3333
description: 'Version of golangci linter to use'
3434
type: 'string'
35-
default: 'v1.53'
35+
default: 'v1.54'
3636

3737
jobs:
3838
# modules checks if the go modules are all up-to-date. While rare with modern
@@ -51,7 +51,6 @@ jobs:
5151
uses: 'actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753' # ratchet:actions/setup-go@v4
5252
with:
5353
go-version: '${{ inputs.go_version }}'
54-
cache: false
5554

5655
- name: 'Check modules'
5756
shell: 'bash'
@@ -82,6 +81,7 @@ jobs:
8281
uses: 'actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753' # ratchet:actions/setup-go@v4
8382
with:
8483
go-version: '${{ inputs.go_version }}'
84+
cache: false
8585

8686
- name: 'Lint (download default configuration)'
8787
id: 'load-default-config'

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jobs:
3838
lint:
3939
uses: 'abcxyz/pkg/.github/workflows/go-lint.yml@main'
4040
with:
41-
go_version: '1.20'
41+
go_version: '1.21'
4242
```
4343
4444
Linting is done via [golangci-lint](https://golangci-lint.run/). If a
@@ -68,7 +68,7 @@ jobs:
6868
lint:
6969
uses: 'abcxyz/pkg/.github/workflows/go-test.yml@main'
7070
with:
71-
go_version: '1.20'
71+
go_version: '1.21'
7272
```
7373

7474
Testing is done via the `go test` command with:

bqutil/query.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,13 @@ func (q *bqQuery[T]) Execute(ctx context.Context) ([]T, error) {
110110
// result, err := RetryQueryEntries(ctx, q, 1, backoff)
111111
func RetryQueryEntries[T any](ctx context.Context, q Query[T], wantCount int, backoff retry.Backoff) ([]T, error) {
112112
logger := logging.FromContext(ctx)
113-
logger.Debugw("Start retrying query", "query", q.String())
113+
logger.DebugContext(ctx, "start retrying query", "query", q.String())
114114

115115
var result []T
116116
if err := retry.Do(ctx, backoff, func(ctx context.Context) error {
117117
entries, err := q.Execute(ctx)
118118
if err != nil {
119-
logger.Debugw("Query failed; will retry", "error", err)
119+
logger.DebugContext(ctx, "query failed; will retry", "error", err)
120120
return retry.RetryableError(err)
121121
}
122122

@@ -126,7 +126,7 @@ func RetryQueryEntries[T any](ctx context.Context, q Query[T], wantCount int, ba
126126
return nil
127127
}
128128

129-
logger.Debugw("Not enough entries; will retry", "gotCount", gotCount, "wantCount", wantCount)
129+
logger.DebugContext(ctx, "not enough entries; will retry", "got_count", gotCount, "want_count", wantCount)
130130
return retry.RetryableError(fmt.Errorf("not enough entries"))
131131
}); err != nil {
132132
return nil, fmt.Errorf("retry backoff exhausted: %w", err)

bqutil/query_test.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ import (
2424
"github.com/abcxyz/pkg/testutil"
2525
"github.com/google/go-cmp/cmp"
2626
"github.com/sethvargo/go-retry"
27-
"go.uber.org/zap/zapcore"
28-
"go.uber.org/zap/zaptest"
2927
)
3028

3129
type fakeQuery[T any] struct {
@@ -94,8 +92,7 @@ func TestRetryQueryEntries(t *testing.T) {
9492
t.Run(tc.name, func(t *testing.T) {
9593
t.Parallel()
9694

97-
ctx := logging.WithLogger(context.Background(),
98-
logging.TestLogger(t, zaptest.Level(zapcore.DebugLevel)))
95+
ctx := logging.WithLogger(context.Background(), logging.TestLogger(t))
9996

10097
wantCount := len(tc.wantEntries)
10198

cli/flags.go

+40
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,16 @@ import (
2020
"flag"
2121
"fmt"
2222
"io"
23+
"log/slog"
2324
"os"
2425
"sort"
2526
"strconv"
2627
"strings"
2728
"time"
2829

30+
"github.com/abcxyz/pkg/logging"
2931
"github.com/abcxyz/pkg/timeutil"
32+
3033
"github.com/kr/text"
3134
"github.com/posener/complete/v2"
3235
"github.com/posener/complete/v2/predict"
@@ -868,6 +871,43 @@ func (f *FlagSection) Uint64Var(i *Uint64Var) {
868871
})
869872
}
870873

874+
type LogLevelVar struct {
875+
Logger *slog.Logger
876+
}
877+
878+
func (f *FlagSection) LogLevelVar(i *LogLevelVar) {
879+
parser := func(s string) (slog.Level, error) {
880+
v, err := logging.LookupLevel(s)
881+
if err != nil {
882+
return 0, err
883+
}
884+
return v, nil
885+
}
886+
887+
printer := func(v slog.Level) string { return logging.LevelString(v) }
888+
889+
setter := func(_ *slog.Level, val slog.Level) { logging.SetLevel(i.Logger, val) }
890+
891+
// trick the CLI into thinking we need a value to set.
892+
var fake slog.Level
893+
894+
levelNames := logging.LevelNames()
895+
896+
Flag(f, &Var[slog.Level]{
897+
Name: "log-level",
898+
Aliases: []string{"l"},
899+
Usage: `Sets the logging verbosity. Valid values include: ` +
900+
strings.Join(levelNames, ",") + `.`,
901+
Example: "warn",
902+
Default: slog.LevelInfo,
903+
Predict: predict.Set(levelNames),
904+
Target: &fake,
905+
Parser: parser,
906+
Printer: printer,
907+
Setter: setter,
908+
})
909+
}
910+
871911
// wrapAtLengthWithPadding wraps the given text at the maxLineLength, taking
872912
// into account any provided left padding.
873913
func wrapAtLengthWithPadding(s string, pad int) string {

cli/flags_test.go

+64
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,16 @@
1515
package cli
1616

1717
import (
18+
"context"
1819
"flag"
1920
"fmt"
2021
"io"
22+
"log/slog"
2123
"reflect"
2224
"strings"
2325
"testing"
2426

27+
"github.com/abcxyz/pkg/logging"
2528
"github.com/abcxyz/pkg/testutil"
2629
"github.com/google/go-cmp/cmp"
2730
)
@@ -314,3 +317,64 @@ func ExampleFlagSet_AfterParse_checkIfError() {
314317
func ptrTo[T any](v T) *T {
315318
return &v
316319
}
320+
321+
func TestLogLevelVar(t *testing.T) {
322+
t.Parallel()
323+
324+
ctx := context.Background()
325+
326+
cases := []struct {
327+
name string
328+
args []string
329+
330+
wantLevel slog.Level
331+
wantError string
332+
}{
333+
{
334+
name: "empty",
335+
args: nil,
336+
wantLevel: slog.LevelInfo,
337+
},
338+
{
339+
name: "long",
340+
args: []string{"-log-level", "debug"},
341+
wantLevel: slog.LevelDebug,
342+
},
343+
{
344+
name: "short",
345+
args: []string{"-l", "debug"},
346+
wantLevel: slog.LevelDebug,
347+
},
348+
{
349+
name: "invalid",
350+
args: []string{"-log-level", "pants"},
351+
wantError: `invalid value "pants" for flag -log-level`,
352+
},
353+
}
354+
355+
for _, tc := range cases {
356+
tc := tc
357+
358+
t.Run(tc.name, func(t *testing.T) {
359+
t.Parallel()
360+
361+
logger := logging.DefaultLogger()
362+
363+
set := NewFlagSet()
364+
f := set.NewSection("FLAGS")
365+
366+
f.LogLevelVar(&LogLevelVar{
367+
Logger: logger,
368+
})
369+
370+
err := set.Parse(tc.args)
371+
if diff := testutil.DiffErrString(err, tc.wantError); diff != "" {
372+
t.Error(diff)
373+
}
374+
375+
if !logger.Handler().Enabled(ctx, tc.wantLevel) {
376+
t.Errorf("expected handler to be at least %s", tc.wantLevel)
377+
}
378+
})
379+
}
380+
}

containertest/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ jobs:
101101
steps:
102102
- uses: actions/setup-go@v4
103103
with:
104-
go-version: '1.20' # Optional
104+
go-version: '1.21' # Optional
105105
```
106106
107107
... and *don't* do this:
@@ -111,5 +111,5 @@ jobs:
111111
test:
112112
name: Go Test
113113
runs-on: ubuntu-latest
114-
container: golang:1.20 # DON'T DO THIS
114+
container: golang:1.21 # DON'T DO THIS
115115
```

gcputil/gcputil.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func ProjectID(ctx context.Context) string {
4343

4444
v, err := metadata.ProjectID()
4545
if err != nil {
46-
logging.FromContext(ctx).Errorw("failed to get project id", "error", err)
46+
logging.FromContext(ctx).ErrorContext(ctx, "failed to get project id", "error", err)
4747
return ""
4848
}
4949
return v

0 commit comments

Comments
 (0)