Skip to content

Commit

Permalink
feat: add unary and stream server interceptors to logging configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
tolgaOzen committed Jan 15, 2024
1 parent eff5d42 commit 83c3a0a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
16 changes: 16 additions & 0 deletions internal/servers/server.go
Expand Up @@ -10,6 +10,8 @@ import (
"net/http/pprof"
"time"

"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"

"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/ratelimit"

grpcAuth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
Expand Down Expand Up @@ -100,6 +102,7 @@ func NewContainer(
func (s *Container) Run(
ctx context.Context,
srv *config.Server,
logger *slog.Logger,
dst *config.Distributed,
authentication *config.Authn,
profiler *config.Profiler,
Expand All @@ -109,16 +112,22 @@ func (s *Container) Run(

limiter := middleware.NewRateLimiter(srv.RateLimit) // for example 1000 req/sec

lopts := []logging.Option{
logging.WithLogOnEvents(logging.StartCall, logging.FinishCall),
}

unaryInterceptors := []grpc.UnaryServerInterceptor{
grpcValidator.UnaryServerInterceptor(),
grpcRecovery.UnaryServerInterceptor(),
ratelimit.UnaryServerInterceptor(limiter),
logging.UnaryServerInterceptor(InterceptorLogger(logger), lopts...),
}

streamingInterceptors := []grpc.StreamServerInterceptor{
grpcValidator.StreamServerInterceptor(),
grpcRecovery.StreamServerInterceptor(),
ratelimit.StreamServerInterceptor(limiter),
logging.StreamServerInterceptor(InterceptorLogger(logger), lopts...),
}

// Configure authentication based on the provided method ("preshared" or "oidc").
Expand Down Expand Up @@ -364,3 +373,10 @@ func (s *Container) Run(

return nil
}

// InterceptorLogger adapts slog logger to interceptor logger.
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...)
})
}
1 change: 1 addition & 0 deletions pkg/cmd/serve.go
Expand Up @@ -374,6 +374,7 @@ func serve() func(cmd *cobra.Command, args []string) error {
return container.Run(
ctx,
&cfg.Server,
logger,
&cfg.Distributed,
&cfg.Authn,
&cfg.Profiler,
Expand Down

0 comments on commit 83c3a0a

Please sign in to comment.