簡體   English   中英

如何為 Python 異步 gRPC 客戶端實現日志攔截器?

[英]How to implement a logging Interceptor for Python async gRPC client?

我正在嘗試使用gRPC AsyncIO API為異步 gRPC 客戶端實現接受/錯誤日志記錄。 我想在一個地方而不是在每個請求中處理常見錯誤(例如StatusCode.UNAVAILABLE )。

使用response.exception()的同步版本很容易:

class LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor):
    def __init__(self, logger: Logger):
        self.logger = logger

    def intercept_unary_unary(self, continuation, client_call_details, request):
        self.logger.debug(f"{request=}")
        response = continuation(client_call_details, request)
        if response.exception():
            self.logger.exception(f"{response.code()}")
        return response

但是當使用異步攔截器時,事情會變得更加復雜。

我嘗試使用 try / except,期待await返回響應,但這並沒有導致任何結果,因為 await continuation返回未完成的UnaryUnaryCall並且它沒有方法.exception

# this does not work
class LoggingClientInterceptor(grpc.aio.UnaryUnaryClientInterceptor):
    def __init__(self, logger: Logger):
        self.logger = logger

    async def intercept_unary_unary(self, continuation, client_call_details, request):
        self.logger.debug(f"{request=}")
        try:
            response = await continuation(client_call_details, request)
            return response
        except Exception as exc:
            self.logger.exception(f"{exc}")

我可以等待響應代碼並將其與 OK 進行比較,然后拋出異常,但在我看來,這在某種程度上是錯誤的方式:如果我想添加另一個攔截器怎么辦?

code = await response.code()
if code != grpc.StatusCode.OK:
    raise SmthException

我已經廣泛搜索,包括官方存儲庫中的代碼,但沒有找到異步攔截器的好例子

如果有人能給我看參考樣品,我會很高興。

遇到類似問題,稍微調整一下代碼。

class LoggingClientInterceptor(grpc.aio.UnaryUnaryClientInterceptor):
    def __init__(self, logger: Logger):
        self.logger = logger

    async def intercept_unary_unary(self, continuation, client_call_details, request):
        self.logger.debug(f"{request=}")
        try:
            undone_call = await continuation(client_call_details, request)
            response = await undone_call
            return response
        except Exception as exc:
            self.logger.exception(f"{exc}")
            raise exc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM