Skip to content

Commit

Permalink
Use custom grpc logger (#1241)
Browse files Browse the repository at this point in the history
Suppress ServerMetadata error log on routing error.
  • Loading branch information
sesposito authored Jul 9, 2024
1 parent 13603b0 commit 3957a84
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
23 changes: 22 additions & 1 deletion server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"database/sql"
"encoding/base64"
"fmt"
"google.golang.org/grpc/grpclog"
"math"
"net"
"net/http"
Expand Down Expand Up @@ -112,6 +113,10 @@ func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, p
}
grpcServer := grpc.NewServer(serverOpts...)

// Set grpc logger
grpcLogger := NewGrpcCustomLogger(logger)
grpclog.SetLoggerV2(grpcLogger)

s := &ApiServer{
logger: logger,
db: db,
Expand Down Expand Up @@ -151,6 +156,7 @@ func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, p
// Should start after GRPC server itself because RegisterNakamaHandlerFromEndpoint below tries to dial GRPC.
ctx := context.Background()
grpcGateway := grpcgw.NewServeMux(
grpcgw.WithRoutingErrorHandler(handleRoutingError),
grpcgw.WithMetadata(func(ctx context.Context, r *http.Request) metadata.MD {
// For RPC GET operations pass through any custom query parameters.
if r.Method != "GET" || !strings.HasPrefix(r.URL.Path, "/v2/rpc/") {
Expand All @@ -166,7 +172,7 @@ func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, p
}
p["q_"+k] = vs
}
return metadata.MD(p)
return p
}),
grpcgw.WithMarshalerOption(grpcgw.MIMEWildcard, &grpcgw.HTTPBodyMarshaler{
Marshaler: &grpcgw.JSONPb{
Expand Down Expand Up @@ -594,3 +600,18 @@ func traceApiAfter(ctx context.Context, logger *zap.Logger, metrics Metrics, ful

metrics.ApiAfter(fullMethodName, time.Since(start), err != nil)
}

func handleRoutingError(ctx context.Context, mux *grpcgw.ServeMux, marshaler grpcgw.Marshaler, w http.ResponseWriter, r *http.Request, httpStatus int) {
sterr := status.Error(codes.Internal, "Unexpected routing error")
switch httpStatus {
case http.StatusBadRequest:
sterr = status.Error(codes.InvalidArgument, http.StatusText(httpStatus))
case http.StatusMethodNotAllowed:
sterr = status.Error(codes.Unimplemented, http.StatusText(httpStatus))
case http.StatusNotFound:
sterr = status.Error(codes.NotFound, http.StatusText(httpStatus))
}

// Set empty ServerMetadata to prevent logging error on nil metadata.
grpcgw.DefaultHTTPErrorHandler(grpcgw.NewServerMetadataContext(ctx, grpcgw.ServerMetadata{}), mux, marshaler, w, r, sterr)
}
28 changes: 28 additions & 0 deletions server/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,31 @@ func RedirectStdLog(logger *zap.Logger) {
skipLogger := logger.WithOptions(zap.AddCallerSkip(3))
log.SetOutput(&RedirectStdLogWriter{skipLogger})
}

type grpcCustomLogger struct {
*zap.SugaredLogger
}

// https://github.com/grpc/grpc-go/blob/master/grpclog/loggerv2.go
func NewGrpcCustomLogger(logger *zap.Logger) grpcCustomLogger {
sLogger := logger.Sugar()
return grpcCustomLogger{
sLogger,
}
}

func (g grpcCustomLogger) Warning(args ...any) {
g.Warn(args...)
}

func (g grpcCustomLogger) Warningln(args ...any) {
g.Warnln(args...)
}

func (g grpcCustomLogger) Warningf(format string, args ...any) {
g.Warnf(format, args...)
}

func (g grpcCustomLogger) V(l int) bool {
return int(g.Level()) <= l
}

0 comments on commit 3957a84

Please sign in to comment.