Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example: use slog instead of go-kit #735

Merged
merged 1 commit into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 13 additions & 26 deletions examples/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ package main

import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"syscall"
"time"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
grpcprom "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout"
Expand All @@ -38,29 +36,18 @@ const (
targetGRPCAddr = "localhost:8080"
)

// interceptorLogger adapts go-kit logger to interceptor logger.
// interceptorLogger adapts slog logger to interceptor logger.
// This code is simple enough to be copied and not imported.
func interceptorLogger(l log.Logger) logging.Logger {
return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) {
largs := append([]any{"msg", msg}, fields...)
switch lvl {
case logging.LevelDebug:
_ = level.Debug(l).Log(largs...)
case logging.LevelInfo:
_ = level.Info(l).Log(largs...)
case logging.LevelWarn:
_ = level.Warn(l).Log(largs...)
case logging.LevelError:
_ = level.Error(l).Log(largs...)
default:
panic(fmt.Sprintf("unknown level %v", lvl))
}
func interceptorLogger(l *slog.Logger) logging.Logger {
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
l.Log(ctx, slog.Level(lvl), msg, fields...)
})
}

func main() {
// Setup logging.
logger := log.NewLogfmtLogger(os.Stderr)
rpcLogger := log.With(logger, "service", "gRPC/client", "component", component)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{}))
rpcLogger := logger.With("service", "gRPC/client", "component", component)
logTraceID := func(ctx context.Context) logging.Fields {
if span := trace.SpanContextFromContext(ctx); span.IsSampled() {
return logging.Fields{"traceID", span.TraceID().String()}
Expand All @@ -86,7 +73,7 @@ func main() {
// Set up OTLP tracing (stdout for debug).
exporter, err := stdout.New(stdout.WithPrettyPrint())
if err != nil {
level.Error(logger).Log("err", err)
logger.Error("failed to init exporter", "err", err)
os.Exit(1)
}
tp := sdktrace.NewTracerProvider(
Expand All @@ -110,7 +97,7 @@ func main() {
logging.StreamClientInterceptor(interceptorLogger(rpcLogger), logging.WithFieldsFromContext(logTraceID))),
)
if err != nil {
level.Error(logger).Log("err", err)
logger.Error("failed to init gRPC client", "err", err)
os.Exit(1)
}

Expand Down Expand Up @@ -148,18 +135,18 @@ func main() {
},
))
httpSrv.Handler = m
level.Info(logger).Log("msg", "starting HTTP server", "addr", httpSrv.Addr)
logger.Info("starting HTTP server", "addr", httpSrv.Addr)
return httpSrv.ListenAndServe()
}, func(error) {
if err := httpSrv.Close(); err != nil {
level.Error(logger).Log("msg", "failed to stop web server", "err", err)
logger.Error("failed to stop web server", "err", err)
}
})

g.Add(run.SignalHandler(context.Background(), syscall.SIGINT, syscall.SIGTERM))

if err := g.Run(); err != nil {
level.Error(logger).Log("err", err)
logger.Error("program interrupted", "err", err)
os.Exit(1)
}
}
2 changes: 0 additions & 2 deletions examples/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ go 1.22
toolchain go1.23.1

require (
github.com/go-kit/log v0.2.1
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.0.0
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0
github.com/oklog/run v1.1.0
Expand All @@ -22,7 +21,6 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/google/uuid v1.6.0 // indirect
Expand Down
4 changes: 0 additions & 4 deletions examples/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
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/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
Expand Down
40 changes: 13 additions & 27 deletions examples/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ package main

import (
"context"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"runtime/debug"
"syscall"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
grpcprom "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
Expand Down Expand Up @@ -43,30 +41,18 @@ const (
httpAddr = ":8081"
)

// interceptorLogger adapts go-kit logger to interceptor logger.
// interceptorLogger adapts slog logger to interceptor logger.
// This code is simple enough to be copied and not imported.
func interceptorLogger(l log.Logger) logging.Logger {
return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) {
largs := append([]any{"msg", msg}, fields...)
switch lvl {
case logging.LevelDebug:
_ = level.Debug(l).Log(largs...)
case logging.LevelInfo:
_ = level.Info(l).Log(largs...)
case logging.LevelWarn:
_ = level.Warn(l).Log(largs...)
case logging.LevelError:
_ = level.Error(l).Log(largs...)
default:
panic(fmt.Sprintf("unknown level %v", lvl))
}
func interceptorLogger(l *slog.Logger) logging.Logger {
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
l.Log(ctx, slog.Level(lvl), msg, fields...)
})
}

func main() {
// Setup logging.
logger := log.NewLogfmtLogger(os.Stderr)
rpcLogger := log.With(logger, "service", "gRPC/server", "component", component)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{}))
rpcLogger := logger.With("service", "gRPC/server", "component", component)
logTraceID := func(ctx context.Context) logging.Fields {
if span := trace.SpanContextFromContext(ctx); span.IsSampled() {
return logging.Fields{"traceID", span.TraceID().String()}
Expand All @@ -92,7 +78,7 @@ func main() {
// Set up OTLP tracing (stdout for debug).
exporter, err := stdout.New(stdout.WithPrettyPrint())
if err != nil {
level.Error(logger).Log("err", err)
logger.Error("failed to init exporter", "err", err)
os.Exit(1)
}
tp := sdktrace.NewTracerProvider(
Expand Down Expand Up @@ -129,7 +115,7 @@ func main() {
})
grpcPanicRecoveryHandler := func(p any) (err error) {
panicsTotal.Inc()
level.Error(rpcLogger).Log("msg", "recovered from panic", "panic", p, "stack", debug.Stack())
rpcLogger.Error("recovered from panic", "panic", p, "stack", debug.Stack())
return status.Errorf(codes.Internal, "%s", p)
}

Expand Down Expand Up @@ -158,7 +144,7 @@ func main() {
if err != nil {
return err
}
level.Info(logger).Log("msg", "starting gRPC server", "addr", l.Addr().String())
logger.Info("starting gRPC server", "addr", l.Addr().String())
return grpcSrv.Serve(l)
}, func(err error) {
grpcSrv.GracefulStop()
Expand All @@ -177,18 +163,18 @@ func main() {
},
))
httpSrv.Handler = m
level.Info(logger).Log("msg", "starting HTTP server", "addr", httpSrv.Addr)
logger.Info("starting HTTP server", "addr", httpSrv.Addr)
return httpSrv.ListenAndServe()
}, func(error) {
if err := httpSrv.Close(); err != nil {
level.Error(logger).Log("msg", "failed to stop web server", "err", err)
logger.Error("failed to stop web server", "err", err)
}
})

g.Add(run.SignalHandler(context.Background(), syscall.SIGINT, syscall.SIGTERM))

if err := g.Run(); err != nil {
level.Error(logger).Log("err", err)
logger.Error("program interrupted", "err", err)
os.Exit(1)
}
}
Loading