Skip to content

Commit

Permalink
added request logger to the grpc server
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderStorm committed Oct 15, 2023
1 parent 29fcab9 commit 6c4981b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
12 changes: 0 additions & 12 deletions server/backend/rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,15 @@ package backend
import (
"context"
"errors"
"net"

pb "github.com/TUM-Dev/Campus-Backend/server/api/tumdev"
"github.com/TUM-Dev/Campus-Backend/server/backend/ios_notifications/apns"
"github.com/TUM-Dev/Campus-Backend/server/model"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gorm.io/gorm"
)

func (s *CampusServer) GRPCServe(l net.Listener) error {
grpcServer := grpc.NewServer()
pb.RegisterCampusServer(grpcServer, s)
if err := grpcServer.Serve(l); err != nil {
log.WithError(err).Fatal("failed to serve")
}
return grpcServer.Serve(l)
}

type CampusServer struct {
pb.UnimplementedCampusServer
db *gorm.DB
Expand Down
16 changes: 15 additions & 1 deletion server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func main() {
httpMux.Handle("/swagger/", http.FileServer(http.FS(swagfs)))

// Main GRPC Server
grpcServer := grpc.NewServer()
grpcServer := grpc.NewServer(grpc.UnaryInterceptor(UnaryRequestLogger), grpc.StreamInterceptor(StreamRequestLogger))
pb.RegisterCampusServer(grpcServer, campusService)
reflection.Register(grpcServer)

Expand Down Expand Up @@ -121,6 +121,20 @@ func main() {
}
}

func UnaryRequestLogger(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
start := time.Now()
resp, err := handler(ctx, req)
fields := log.Fields{"elapsed": time.Now().Sub(start)}
log.WithContext(ctx).WithFields(fields).WithError(err).Info(info.FullMethod)
return resp, err
}
func StreamRequestLogger(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
start := time.Now()
err := handler(srv, stream)
log.WithField("elapsed", time.Now().Sub(start)).WithError(err).Info(info.FullMethod)
return err
}

// setupDB connects to the database and migrates it if necessary
func setupDB() *gorm.DB {
dbHost := os.Getenv("DB_DSN")
Expand Down

0 comments on commit 6c4981b

Please sign in to comment.