Skip to content

Commit

Permalink
Migrate to slog (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
majst01 authored Mar 5, 2024
1 parent 1c665e5 commit 268aee5
Show file tree
Hide file tree
Showing 19 changed files with 82 additions and 166 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ protoc-ci: third-party
.PHONY: mocks
mocks:
rm -rf api/duros/v2/mocks/*
docker run --user $$(id -u):$$(id -g) --rm -w /work -v ${PWD}:/work vektra/mockery:v2.41.0 -r --all --keeptree --dir api/duros/v2 --output api/duros/v2/mocks
docker run --user $$(id -u):$$(id -g) --rm -w /work -v ${PWD}:/work vektra/mockery:v2.42.0 -r --all --keeptree --dir api/duros/v2 --output api/duros/v2/mocks
2 changes: 1 addition & 1 deletion api/duros/v2/mocks/DurosAPIClient.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/DurosAPIServer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/DurosAPI_FetchLogsClient.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/DurosAPI_FetchLogsServer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/UnsafeDurosAPIServer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isCreatePolicyRequest_Policy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isCreateVolumeRequest_QosPolicyID.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isEvent_ComponentInfo.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isPolicy_Info.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isQoSRateLimitPolicy_QoSLimit.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isSchedulePolicy_SchedulePolicies.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isUpdatePolicyRequest_Policy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/duros/v2/mocks/isUpdateVolumeRequest_QosPolicyID.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

80 changes: 30 additions & 50 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"log/slog"
"math/rand"
"os"
"strconv"
"time"

grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"

grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/balancer/roundrobin"
Expand Down Expand Up @@ -48,7 +46,7 @@ const (
type client struct {
eps EPs
conn *grpc.ClientConn
log *zap.SugaredLogger
log *slog.Logger
}

// DialConfig is the configuration to create a duros-api connection
Expand All @@ -58,7 +56,7 @@ type DialConfig struct {
Token string
Credentials *Credentials
ByteCredentials *ByteCredentials
Log *zap.SugaredLogger
Log *slog.Logger
// UserAgent to use, if empty duros-go is used
UserAgent string
}
Expand Down Expand Up @@ -115,7 +113,7 @@ func Dial(ctx context.Context, config DialConfig) (durosv2.DurosAPIClient, error
ua = config.UserAgent
}

log.Infow("connecting...",
log.Info("connecting...",
"client", ua,
"targets", config.Endpoints,
"client-id", id,
Expand All @@ -126,16 +124,6 @@ func Dial(ctx context.Context, config DialConfig) (durosv2.DurosAPIClient, error
log: log,
}

zapOpts := []grpc_zap.Option{
grpc_zap.WithLevels(grpcToZapLevel),
}
interceptors := []grpc.UnaryClientInterceptor{
grpc_zap.UnaryClientInterceptor(log.Desugar(), zapOpts...),
grpc_zap.PayloadUnaryClientInterceptor(log.Desugar(),
func(context.Context, string) bool { return true },
),
}

// these are broadly in line with the expected server SLOs:
kal := keepalive.ClientParameters{
Time: 10 * time.Second,
Expand All @@ -162,11 +150,11 @@ func Dial(ctx context.Context, config DialConfig) (durosv2.DurosAPIClient, error
}

opts := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithDisableRetry(),
grpc.WithUserAgent(ua),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(interceptors...)),
grpc.WithChainUnaryInterceptor(
logging.UnaryClientInterceptor(interceptorLogger(log))),
grpc.WithKeepaliveParams(kal),
grpc.WithConnectParams(cp),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, roundrobin.Name)),
Expand All @@ -177,10 +165,10 @@ func Dial(ctx context.Context, config DialConfig) (durosv2.DurosAPIClient, error
// Configure tls ca certificate based auth if credentials are given
switch config.Scheme {
case GRPC:
log.Infof("connecting insecurely")
log.Info("connecting insecurely")
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
case GRPCS:
log.Infof("connecting securely")
log.Info("connecting securely")
if config.Credentials != nil {
creds, err := config.Credentials.getTransportCredentials()
if err != nil {
Expand Down Expand Up @@ -208,11 +196,11 @@ func Dial(ctx context.Context, config DialConfig) (durosv2.DurosAPIClient, error
opts...,
)
if err != nil {
log.Errorw("failed to connect", "endpoints", config.Endpoints.String(), "error", err.Error())
log.Error("failed to connect", "endpoints", config.Endpoints.String(), "error", err.Error())
return nil, err
}

log.Infof("connected")
log.Info("connected")

c := durosv2.NewDurosAPIClient(res.conn)
return c, nil
Expand All @@ -232,33 +220,6 @@ func (tokenAuth) RequireTransportSecurity() bool {
return true
}

func grpcToZapLevel(code codes.Code) zapcore.Level {
switch code {
case codes.OK,
codes.Canceled,
codes.DeadlineExceeded,
codes.NotFound,
codes.Unavailable:
return zapcore.InfoLevel
case codes.Aborted,
codes.AlreadyExists,
codes.FailedPrecondition,
codes.InvalidArgument,
codes.OutOfRange,
codes.PermissionDenied,
codes.ResourceExhausted,
codes.Unauthenticated:
return zapcore.WarnLevel
case codes.DataLoss,
codes.Internal,
codes.Unimplemented,
codes.Unknown:
return zapcore.ErrorLevel
default:
return zapcore.ErrorLevel
}
}

func (c Credentials) getTransportCredentials() (credentials.TransportCredentials, error) {
certPool, err := x509.SystemCertPool()
if err != nil {
Expand Down Expand Up @@ -318,3 +279,22 @@ func (c ByteCredentials) getTransportCredentials() (credentials.TransportCredent
})
return creds, nil
}

// interceptorLogger adapts slog logger to interceptor logger.
// This code is simple enough to be copied and not imported.
func interceptorLogger(l *slog.Logger) logging.Logger {
return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) {
switch lvl {
case logging.LevelDebug:
l.Debug(msg, fields...)
case logging.LevelInfo:
l.Info(msg, fields...)
case logging.LevelWarn:
l.Warn(msg, fields...)
case logging.LevelError:
l.Error(msg, fields...)
default:
panic(fmt.Sprintf("unknown level %v", lvl))
}
})
}
8 changes: 2 additions & 6 deletions cmd/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"context"
"flag"
"fmt"
"log/slog"

"github.com/google/uuid"
duros "github.com/metal-stack/duros-go"
v2 "github.com/metal-stack/duros-go/api/duros/v2"
"go.uber.org/zap"
)

const (
Expand Down Expand Up @@ -55,10 +55,6 @@ func main() {

flag.Parse()

zlog, err := zap.NewProduction()
if err != nil {
panic((err))
}
var grpcScheme duros.GRPCScheme
switch scheme {
case "grpc":
Expand All @@ -74,7 +70,7 @@ func main() {
Endpoints: duros.MustParseCSV(endpoints),
Scheme: grpcScheme,
Token: token,
Log: zlog.Sugar(),
Log: slog.Default(),
UserAgent: "duros-go-cli",
}
if caFile != "" && certFile != "" && keyFile != "" && serverName != "" {
Expand Down
21 changes: 10 additions & 11 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,24 @@ go 1.22
require (
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/uuid v1.6.0
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/stretchr/testify v1.8.4
go.uber.org/zap v1.26.0
google.golang.org/genproto/googleapis/api v0.0.0-20240213162025-012b6fc9bca9
google.golang.org/grpc v1.61.1
github.com/stretchr/testify v1.9.0
google.golang.org/genproto/googleapis/api v0.0.0-20240304212257-790db918fca8
google.golang.org/grpc v1.62.0
google.golang.org/protobuf v1.32.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
golang.org/x/net v0.22.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240304212257-790db918fca8 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit 268aee5

Please sign in to comment.