Skip to content

Commit

Permalink
Replace zap with slog
Browse files Browse the repository at this point in the history
Prefer the standard library to limit dependencies.
  • Loading branch information
jschaf committed Jan 2, 2024
1 parent eed4662 commit 8a11235
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 46 deletions.
6 changes: 2 additions & 4 deletions cmd/pggen/pggen.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
Expand All @@ -14,7 +15,6 @@ import (
"github.com/jschaf/pggen/internal/flags"
"github.com/jschaf/pggen/internal/texts"
"github.com/peterbourgon/ff/v3/ffcli"
"go.uber.org/zap"
)

// Set via ldflags for release binaries.
Expand Down Expand Up @@ -96,8 +96,6 @@ func newGenCmd() *ffcli.Command {
"like 'device_type=github.com/jschaf/pggen.DeviceType'")
inlineParamCount := fset.Int("inline-param-count", 2,
"number of params (inclusive) to inline when calling querier methods; 0 always generates a struct")
logLvl := zap.InfoLevel
fset.Var(&logLvl, "log", "log level: debug, info, or error")
goSubCmd := &ffcli.Command{
Name: "go",
ShortUsage: "pggen gen go --query-glob glob [--schema-glob <glob>]... [flags]",
Expand Down Expand Up @@ -168,7 +166,7 @@ func newGenCmd() *ffcli.Command {
OutputDir: outDir,
Acronyms: acros,
TypeOverrides: typeOverrides,
LogLevel: logLvl,
LogLevel: slog.LevelInfo,
InlineParamCount: *inlineParamCount,
})
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions example/acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/jackc/pgx/v4"
"github.com/jschaf/pggen/internal/errs"
"github.com/jschaf/pggen/internal/pgdocker"
"go.uber.org/zap/zaptest"
"math/rand"
"os"
"os/exec"
Expand Down Expand Up @@ -261,7 +260,7 @@ func TestExamples(t *testing.T) {
// a new database in the Postgres cluster.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
docker, err := pgdocker.Start(ctx, nil, zaptest.NewLogger(t).Sugar())
docker, err := pgdocker.Start(ctx, nil)
if err != nil {
t.Fatal(err)
}
Expand Down
25 changes: 5 additions & 20 deletions generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import (
"github.com/jschaf/pggen/internal/pgdocker"
"github.com/jschaf/pggen/internal/pginfer"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
gotok "go/token"
"log/slog"
"os"
"path/filepath"
"time"
Expand Down Expand Up @@ -60,7 +59,7 @@ type GenerateOptions struct {
// A map from a Postgres type name to a fully qualified Go type.
TypeOverrides map[string]string
// What log level to log at.
LogLevel zapcore.Level
LogLevel slog.Level
// How many params to inline when calling querier methods.
// Set to 0 to always create a struct for params.
InlineParamCount int
Expand All @@ -82,20 +81,10 @@ func Generate(opts GenerateOptions) (mErr error) {
return fmt.Errorf("output dir must be set")
}

// Logger.
logCfg := zap.NewDevelopmentConfig()
logCfg.Level = zap.NewAtomicLevelAt(opts.LogLevel)
logger, err := logCfg.Build()
if err != nil {
return fmt.Errorf("create zap logger: %w", err)
}
defer func(logger *zap.Logger) { _ = logger.Sync() }(logger)
l := logger.Sugar()

// Postgres connection.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
pgConn, errEnricher, cleanup, err := connectPostgres(ctx, opts, l)
pgConn, errEnricher, cleanup, err := connectPostgres(ctx, opts)
if err != nil {
return fmt.Errorf("connect postgres: %w", err)
}
Expand Down Expand Up @@ -135,14 +124,10 @@ func Generate(opts GenerateOptions) (mErr error) {

// connectPostgres connects to postgres using connString if given or by
// running a Docker postgres container and connecting to that.
func connectPostgres(
ctx context.Context,
opts GenerateOptions,
l *zap.SugaredLogger,
) (*pgx.Conn, func(error) error, func() error, error) {
func connectPostgres(ctx context.Context, opts GenerateOptions) (*pgx.Conn, func(error) error, func() error, error) {
// Create connection by starting dockerized Postgres.
if opts.ConnString == "" {
client, err := pgdocker.Start(ctx, opts.SchemaFiles, l)
client, err := pgdocker.Start(ctx, opts.SchemaFiles)
if err != nil {
return nil, nil, nil, fmt.Errorf("start dockerized postgres: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ require (
github.com/shopspring/decimal v1.3.1
github.com/stretchr/testify v1.8.4
go.uber.org/multierr v1.11.0
go.uber.org/zap v1.26.0
golang.org/x/mod v0.11.0
)

Expand All @@ -30,6 +29,7 @@ require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/kr/pretty v0.2.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
Expand Down
7 changes: 1 addition & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMe
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v23.0.3+incompatible h1:9GhVsShNWz1hO//9BNg/dpMnZW25KydO4wtVxWAIbho=
github.com/docker/docker v23.0.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig1seQen0cKYlM=
github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
Expand Down Expand Up @@ -158,8 +157,6 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
Expand All @@ -169,8 +166,6 @@ go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9E
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand Down
25 changes: 12 additions & 13 deletions internal/pgdocker/pgdocker.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import (
"github.com/jschaf/pggen/internal/errs"
"github.com/jschaf/pggen/internal/ports"
"go.uber.org/multierr"
"go.uber.org/zap"
"io"
"log/slog"
"os"
"path/filepath"
"regexp"
Expand All @@ -29,20 +29,19 @@ import (
type Client struct {
docker *dockerClient.Client
containerID string // container ID if started, empty otherwise
l *zap.SugaredLogger
connString string
}

// Start builds a Docker image and runs the image in a container.
func Start(ctx context.Context, initScripts []string, l *zap.SugaredLogger) (client *Client, mErr error) {
func Start(ctx context.Context, initScripts []string) (client *Client, mErr error) {
now := time.Now()
dockerCl, err := dockerClient.NewClientWithOpts(dockerClient.FromEnv)
if err != nil {
return nil, fmt.Errorf("create client: %w", err)
}
c := &Client{docker: dockerCl, l: l}
c := &Client{docker: dockerCl}
imageID, err := c.buildImage(ctx, initScripts)
l.Debugf("build image ID: %s", imageID)
slog.DebugContext(ctx, "build image", slog.String("image_id", imageID))
if err != nil {
return nil, fmt.Errorf("build image: %w", err)
}
Expand All @@ -67,7 +66,7 @@ func Start(ctx context.Context, initScripts []string, l *zap.SugaredLogger) (cli
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := client.Stop(ctx); err != nil {
c.l.Errorf("stop pgdocker client: %s", err)
slog.ErrorContext(ctx, "stop pgdocker client", slog.String("error", err.Error()))
}
}
}()
Expand All @@ -77,7 +76,7 @@ func Start(ctx context.Context, initScripts []string, l *zap.SugaredLogger) (cli
if err := c.waitIsReady(ctx); err != nil {
return nil, fmt.Errorf("wait for postgres to be ready: %w", err)
}
c.l.Debugf("started docker postgres in %d ms", time.Since(now).Milliseconds())
slog.DebugContext(ctx, "started docker postgres", slog.Duration("start_duration", time.Since(now)))
return c, nil
}

Expand Down Expand Up @@ -125,7 +124,7 @@ func (c *Client) buildImage(ctx context.Context, initScripts []string) (id strin
}); err != nil {
return "", fmt.Errorf("execute template: %w", err)
}
c.l.Debug("wrote template into buffer")
slog.DebugContext(ctx, "wrote template into buffer", slog.String("dockerfile", dockerfileBuf.String()))

// Tar Dockerfile for build context.
tarBuf := &bytes.Buffer{}
Expand All @@ -147,7 +146,7 @@ func (c *Client) buildImage(ctx context.Context, initScripts []string) (id strin
}

tarR := bytes.NewReader(tarBuf.Bytes())
c.l.Debug("wrote tar dockerfile into buffer")
slog.DebugContext(ctx, "wrote tar dockerfile into buffer")

// Send build request.
opts := types.ImageBuildOptions{Dockerfile: "Dockerfile"}
Expand Down Expand Up @@ -223,12 +222,12 @@ func (c *Client) runContainer(ctx context.Context, imageID string) (string, port
return "", 0, fmt.Errorf("create container: %w", err)
}
containerID := resp.ID
c.l.Debugf("created postgres container ID=%s port=%d", containerID, port)
slog.DebugContext(ctx, "created postgres container", slog.String("container_id", containerID), slog.Int("port", port))
err = c.docker.ContainerStart(ctx, containerID, types.ContainerStartOptions{})
if err != nil {
return "", 0, fmt.Errorf("start container: %w", err)
}
c.l.Debugf("started container ID %s", containerID)
slog.DebugContext(ctx, "started container", slog.String("container_id", containerID))
return containerID, port, nil
}

Expand All @@ -254,11 +253,11 @@ func (c *Client) waitIsReady(ctx context.Context) error {
conn, err := pgx.ConnectConfig(ctx, cfg)
if err == nil {
if err := conn.Close(ctx); err != nil {
c.l.Errorf("close postgres connection: %s", err)
slog.DebugContext(ctx, "close postgres connection", slog.String("error", err.Error()))
}
return nil
}
c.l.Debugf("attempted connection: %s", err)
slog.DebugContext(ctx, "attempted connection", slog.String("error", err.Error()))
<-debounce
}
}
Expand Down

0 comments on commit 8a11235

Please sign in to comment.