From 66bb7d8818ff22b450b82111a1260ca6dfe3486c Mon Sep 17 00:00:00 2001 From: Olivier Cano Date: Mon, 2 Dec 2024 18:32:47 +0100 Subject: [PATCH] example: use slog (#735) Signed-off-by: Olivier Cano --- examples/client/main.go | 39 +++++++++++++-------------------------- examples/go.mod | 2 -- examples/go.sum | 4 ---- examples/server/main.go | 40 +++++++++++++--------------------------- 4 files changed, 26 insertions(+), 59 deletions(-) diff --git a/examples/client/main.go b/examples/client/main.go index 39eb8cfc..d6dd6744 100644 --- a/examples/client/main.go +++ b/examples/client/main.go @@ -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" @@ -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()} @@ -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( @@ -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) } @@ -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) } } diff --git a/examples/go.mod b/examples/go.mod index 5fbf5235..8605bb07 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -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 @@ -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 diff --git a/examples/go.sum b/examples/go.sum index 8b26cc95..677d7fce 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -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= diff --git a/examples/server/main.go b/examples/server/main.go index 740ca358..65f138cd 100644 --- a/examples/server/main.go +++ b/examples/server/main.go @@ -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" @@ -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()} @@ -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( @@ -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) } @@ -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() @@ -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) } }