func DefaultServerInterceptors()

in grpc/interceptor/interceptor.go [90:151]


func DefaultServerInterceptors(options ServerInterceptorLogOptions) []grpc.UnaryServerInterceptor {
	// The first registerred interceptor will be called first.
	// Need to register requestid first to add request-id.
	// Then the logger can get the request-id.
	var apiHandler log.Handler
	var ctxHandler log.Handler

	apiHandlerOptions := &log.HandlerOptions{
		ReplaceAttr: func(groups []string, a log.Attr) log.Attr {
			a.Key = strings.TrimPrefix(a.Key, "grpc.")
			a.Key = strings.ReplaceAll(a.Key, ".", "_")
			return a
		},
	}
	ctxHandlerOptions := &log.HandlerOptions{
		AddSource: true,
		ReplaceAttr: func(groups []string, a log.Attr) log.Attr {
			if a.Key == log.SourceKey {
				// Needed to add to prevent "CtxLog" key from being changed as well
				switch value := a.Value.Any().(type) {
				case *log.Source:
					if strings.Contains(value.File, ".go") {
						a.Key = "location"
					}
				}
			}
			a.Key = strings.TrimPrefix(a.Key, "grpc.")
			a.Key = strings.ReplaceAll(a.Key, ".", "_")
			return a
		},
	}

	if _, ok := options.Logger.Handler().(*log.JSONHandler); ok {
		apiHandler = log.NewJSONHandler(options.APIOutput, apiHandlerOptions)
		ctxHandler = log.NewJSONHandler(options.CtxOutput, ctxHandlerOptions)
	} else {
		apiHandler = log.NewTextHandler(options.APIOutput, apiHandlerOptions)
		ctxHandler = log.NewTextHandler(options.CtxOutput, ctxHandlerOptions)
	}

	apiHandler = apiHandler.WithAttrs(options.APIAttributes)
	ctxHandler = ctxHandler.WithAttrs(options.CtxAttributes)

	apiRequestLogger := log.New(apiHandler).With("source", "ApiRequestLog")
	appCtxlogger := log.New(ctxHandler).With("source", "CtxLog")
	validator, err := protovalidate.New()
	if err != nil {
		panic(err)
	}
	return []grpc.UnaryServerInterceptor{
		protovalidate_middleware.UnaryServerInterceptor(validator),
		requestid.UnaryServerInterceptor(),
		ctxlogger.UnaryServerInterceptor(appCtxlogger, nil),
		logging.UnaryServerInterceptor(
			autologger.InterceptorLogger(apiRequestLogger),
			logging.WithLogOnEvents(logging.FinishCall),
			logging.WithFieldsFromContext(common.GetFields),
		),
		responseheader.UnaryServerInterceptor(httpcommon.MetadataToHeader),
		recovery.UnaryServerInterceptor(common.GetRecoveryOpts()...),
	}
}