added and used LevelHandler

This commit is contained in:
miampf 2024-01-10 13:44:25 +01:00
parent e40a99ca3a
commit 0e4d220c92
No known key found for this signature in database
GPG key ID: 376EAC0E5307A669
7 changed files with 56 additions and 24 deletions

View file

@ -50,8 +50,7 @@ func main() {
if *gRPCDebug { if *gRPCDebug {
logger.ReplaceGRPCLogger(log.WithGroup("gRPC")) logger.ReplaceGRPCLogger(log.WithGroup("gRPC"))
} else { } else {
//TODO(miampf): Find a good way to dynamically increase slog logLevel logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, log.Handler())).WithGroup("gRPC"))
logger.ReplaceGRPCLogger(log.WithGroup("gRPC")).WithIncreasedLevel(slog.LevelWarn)
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())

View file

@ -23,7 +23,6 @@ import (
pb "github.com/edgelesssys/constellation/v2/debugd/service" pb "github.com/edgelesssys/constellation/v2/debugd/service"
"github.com/edgelesssys/constellation/v2/internal/constants" "github.com/edgelesssys/constellation/v2/internal/constants"
"github.com/edgelesssys/constellation/v2/internal/logger" "github.com/edgelesssys/constellation/v2/internal/logger"
"go.uber.org/zap"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/keepalive" "google.golang.org/grpc/keepalive"
) )
@ -157,8 +156,7 @@ func Start(log *slog.Logger, wg *sync.WaitGroup, serv pb.DebugdServer) {
defer wg.Done() defer wg.Done()
grpcLog := log.WithGroup("gRPC") grpcLog := log.WithGroup("gRPC")
// TODO(miampf): Find a way to dynamically increase the log level logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, grpcLog.Handler())))
grpcLog.WithIncreasedLevel(zap.WarnLevel).ReplaceGRPCLogger()
grpcServer := grpc.NewServer( grpcServer := grpc.NewServer(
logger.GetServerStreamInterceptor(grpcLog), logger.GetServerStreamInterceptor(grpcLog),

View file

@ -123,6 +123,52 @@ func middlewareLogger(l *slog.Logger) logging.Logger {
}) })
} }
// LevelHandler copied from the official LevelHandler example in the slog package documentation.
// LevelHandler wraps a Handler with an Enabled method
// that returns false for levels below a minimum.
type LevelHandler struct {
level slog.Leveler
handler slog.Handler
}
// NewLevelHandler returns a LevelHandler with the given level.
// All methods except Enabled delegate to h.
func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
// Optimization: avoid chains of LevelHandlers.
if lh, ok := h.(*LevelHandler); ok {
h = lh.Handler()
}
return &LevelHandler{level, h}
}
// Enabled implements Handler.Enabled by reporting whether
// level is at least as large as h's level.
func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level.Level()
}
// Handle implements Handler.Handle.
func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
return h.handler.Handle(ctx, r)
}
// WithAttrs implements Handler.WithAttrs.
func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
}
// WithGroup implements Handler.WithGroup.
func (h *LevelHandler) WithGroup(name string) slog.Handler {
return NewLevelHandler(h.level, h.handler.WithGroup(name))
}
// Handler returns the Handler wrapped by h.
func (h *LevelHandler) Handler() slog.Handler {
return h.handler
}
// TestWriter is a writer to a testing.T used in tests for logging with slog.
type TestWriter struct { type TestWriter struct {
T *testing.T T *testing.T
} }

View file

@ -21,7 +21,6 @@ import (
"github.com/edgelesssys/constellation/v2/internal/logger" "github.com/edgelesssys/constellation/v2/internal/logger"
"github.com/edgelesssys/constellation/v2/internal/versions/components" "github.com/edgelesssys/constellation/v2/internal/versions/components"
"github.com/edgelesssys/constellation/v2/joinservice/joinproto" "github.com/edgelesssys/constellation/v2/joinservice/joinproto"
"go.uber.org/zap"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials"
@ -59,8 +58,7 @@ func New(
// Run starts the gRPC server on the given port, using the provided tlsConfig. // Run starts the gRPC server on the given port, using the provided tlsConfig.
func (s *Server) Run(creds credentials.TransportCredentials, port string) error { func (s *Server) Run(creds credentials.TransportCredentials, port string) error {
// TODO(miampf): Find a good way to increase slogs log level logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, s.log.Handler())).WithGroup("gRPC"))
s.log.WithIncreasedLevel(zap.WarnLevel).Named("gRPC").ReplaceGRPCLogger()
grpcServer := grpc.NewServer( grpcServer := grpc.NewServer(
grpc.Creds(creds), grpc.Creds(creds),
logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC")), logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC")),
@ -72,7 +70,7 @@ func (s *Server) Run(creds credentials.TransportCredentials, port string) error
if err != nil { if err != nil {
return fmt.Errorf("failed to listen: %s", err) return fmt.Errorf("failed to listen: %s", err)
} }
s.log.Info("Starting join service on %s", lis.Addr().String()) s.log.Info(fmt.Sprintf("Starting join service on %s", lis.Addr().String()))
return grpcServer.Serve(lis) return grpcServer.Serve(lis)
} }
@ -115,7 +113,7 @@ func (s *Server) IssueJoinTicket(ctx context.Context, req *joinproto.IssueJoinTi
return nil, status.Errorf(codes.Internal, "getting components ConfigMap name: %s", err) return nil, status.Errorf(codes.Internal, "getting components ConfigMap name: %s", err)
} }
log.Info("Querying %s ConfigMap for components", componentsConfigMapName) log.Info(fmt.Sprintf("Querying %s ConfigMap for components", componentsConfigMapName))
components, err := s.kubeClient.GetComponents(ctx, componentsConfigMapName) components, err := s.kubeClient.GetComponents(ctx, componentsConfigMapName)
if err != nil { if err != nil {
log.With(slog.Any("error", err)).Error("Failed getting components from ConfigMap") log.With(slog.Any("error", err)).Error("Failed getting components from ConfigMap")

View file

@ -18,7 +18,6 @@ import (
"github.com/edgelesssys/constellation/v2/internal/kms/kms" "github.com/edgelesssys/constellation/v2/internal/kms/kms"
"github.com/edgelesssys/constellation/v2/internal/logger" "github.com/edgelesssys/constellation/v2/internal/logger"
"github.com/edgelesssys/constellation/v2/keyservice/keyserviceproto" "github.com/edgelesssys/constellation/v2/keyservice/keyserviceproto"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
@ -51,11 +50,7 @@ func (s *Server) Run(port string) error {
server := grpc.NewServer(logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC"))) server := grpc.NewServer(logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC")))
keyserviceproto.RegisterAPIServer(server, s) keyserviceproto.RegisterAPIServer(server, s)
// TODO(miampf): Find out a good way to pass an increased Level to slog. logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, s.log.Handler())).WithGroup("gRPC"))
// A reference implementation for something like that exists
// [here](https://pkg.go.dev/log/slog#Handler), however, this would
// utilise structs in the logger package again which is not optimal.
logger.ReplaceGRPCLogger(s.log.WithGroup("gRPC").WithIncreasedLevel(zapcore.WarnLevel))
// start the server // start the server
s.log.Info("Starting Constellation key management service on %s", listener.Addr().String()) s.log.Info("Starting Constellation key management service on %s", listener.Addr().String())

View file

@ -16,7 +16,6 @@ import (
"github.com/edgelesssys/constellation/v2/internal/logger" "github.com/edgelesssys/constellation/v2/internal/logger"
"github.com/edgelesssys/constellation/v2/upgrade-agent/internal/server" "github.com/edgelesssys/constellation/v2/upgrade-agent/internal/server"
"github.com/spf13/afero" "github.com/spf13/afero"
"go.uber.org/zap"
) )
const ( const (
@ -33,8 +32,7 @@ func main() {
if *gRPCDebug { if *gRPCDebug {
logger.ReplaceGRPCLogger(log.WithGroup("gRPC")) logger.ReplaceGRPCLogger(log.WithGroup("gRPC"))
} else { } else {
// TODO(miampf): Find a good way to change log level dynamically logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, log.Handler())).WithGroup("gRPC"))
log.WithGroup("gRPC").WithIncreasedLevel(zap.WarnLevel).ReplaceGRPCLogger()
} }
handler := file.NewHandler(afero.NewOsFs()) handler := file.NewHandler(afero.NewOsFs())

View file

@ -21,7 +21,6 @@ import (
"github.com/edgelesssys/constellation/v2/internal/constants" "github.com/edgelesssys/constellation/v2/internal/constants"
"github.com/edgelesssys/constellation/v2/internal/logger" "github.com/edgelesssys/constellation/v2/internal/logger"
"github.com/edgelesssys/constellation/v2/verify/verifyproto" "github.com/edgelesssys/constellation/v2/verify/verifyproto"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/keepalive" "google.golang.org/grpc/keepalive"
@ -57,8 +56,7 @@ func (s *Server) Run(httpListener, grpcListener net.Listener) error {
var wg sync.WaitGroup var wg sync.WaitGroup
var once sync.Once var once sync.Once
//TODO(miampf): Find a good way to dynamically increase/change log level logger.ReplaceGRPCLogger(slog.New(logger.NewLevelHandler(slog.LevelWarn, s.log.Handler()).WithGroup("grpc")))
s.log.WithIncreasedLevel(zapcore.WarnLevel).Named("grpc").ReplaceGRPCLogger()
grpcServer := grpc.NewServer( grpcServer := grpc.NewServer(
logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC")), logger.GetServerUnaryInterceptor(s.log.WithGroup("gRPC")),
grpc.KeepaliveParams(keepalive.ServerParameters{Time: 15 * time.Second}), grpc.KeepaliveParams(keepalive.ServerParameters{Time: 15 * time.Second}),
@ -74,7 +72,7 @@ func (s *Server) Run(httpListener, grpcListener net.Listener) error {
defer wg.Done() defer wg.Done()
defer grpcServer.GracefulStop() defer grpcServer.GracefulStop()
s.log.Info("Starting HTTP server on %s", httpListener.Addr().String()) s.log.Info(fmt.Sprintf("Starting HTTP server on %s", httpListener.Addr().String()))
httpErr := httpServer.Serve(httpListener) httpErr := httpServer.Serve(httpListener)
if httpErr != nil && httpErr != http.ErrServerClosed { if httpErr != nil && httpErr != http.ErrServerClosed {
once.Do(func() { err = httpErr }) once.Do(func() { err = httpErr })
@ -86,7 +84,7 @@ func (s *Server) Run(httpListener, grpcListener net.Listener) error {
defer wg.Done() defer wg.Done()
defer func() { _ = httpServer.Shutdown(context.Background()) }() defer func() { _ = httpServer.Shutdown(context.Background()) }()
s.log.Info("Starting gRPC server on %s", grpcListener.Addr().String()) s.log.Info(fmt.Sprintf("Starting gRPC server on %s", grpcListener.Addr().String()))
grpcErr := grpcServer.Serve(grpcListener) grpcErr := grpcServer.Serve(grpcListener)
if grpcErr != nil { if grpcErr != nil {
once.Do(func() { err = grpcErr }) once.Do(func() { err = grpcErr })