From 8fdeee740037a58320c7c119980e8a152c28cee2 Mon Sep 17 00:00:00 2001 From: Igor Shishkin Date: Sun, 21 Jul 2024 10:25:45 +0300 Subject: [PATCH] Add logging to manager (#75) Signed-off-by: Igor Shishkin --- cmd/manager/main.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 1a655b1..f55a535 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -3,6 +3,7 @@ package main import ( "context" "database/sql" + "fmt" "net" "net/http" "runtime/debug" @@ -12,6 +13,7 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" + "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery" "github.com/kelseyhightower/envconfig" _ "github.com/lib/pq" @@ -110,9 +112,11 @@ func main() { gs := grpc.NewServer( grpc.ChainUnaryInterceptor( + logging.UnaryServerInterceptor(interceptorLogger()), recovery.UnaryServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)), ), grpc.ChainStreamInterceptor( + logging.StreamServerInterceptor(interceptorLogger()), recovery.StreamServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)), ), ) @@ -136,3 +140,30 @@ func grpcPanicRecoveryHandler(p any) (err error) { log.Errorf("recovered from panic: %s", debug.Stack()) return status.Errorf(codes.Internal, "%s", p) } + +func interceptorLogger() logging.Logger { + return logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) { + switch lvl { + case logging.LevelDebug: + log.Debugf("%s: %s", msg, formatFields(fields)) + case logging.LevelInfo: + log.Infof("%s: %s", msg, formatFields(fields)) + case logging.LevelWarn: + log.Warnf("%s: %s", msg, formatFields(fields)) + case logging.LevelError: + log.Errorf("%s: %s", msg, formatFields(fields)) + default: + panic(fmt.Sprintf("unknown level %v", lvl)) + } + }) +} + +func formatFields(in []any) (out string) { + for i := 1; i < len(in); i += 2 { + key := in[i-1] + value := in[i] + + out += fmt.Sprintf("%v=%v; ", key, value) + } + return out +}