我有一个用例,我需要为单个函数使用两种装饰器类型的注释。我有一个休息端点,我需要使用普罗米修斯客户端模块捕获指标。我正在尝试类似的方法,但它不起作用。
rest_app = APIRouter(prefix='/rest')
TIME_METRICS_ANNOTATION = Gauge('request_time_taken', 'Time Taken for My Endpoint')
@TIME_METRICS_ANNOTATION.time()
@rest_app.post("/endpoint")
async def my_endpoint(request: Request):
# body
我也尝试交换注释,但无论哪个注释紧接在方法定义之上,只有那个注释生效,另一个注释不生效。
我知道还有一些其他方法可以做到这一点,如下所示,但使用注释的初始方法将是更清晰的代码。
@rest_app.post("/endpoint")
async def my_endpoint(request: Request):
start_time = time.process_time()
# body
TIME_METRICS_ANNOTATION.set(time.process_time() - start_time)
或
@rest_app.post("/endpoint")
async def my_endpoint(request: Request):
my_endpoint_body(request)
@TIME_METRICS_ANNOTATION.time()
def my_endpoint_body(request: Request):
# body
如有任何帮助,我们将不胜感激。
旁注查询:是否有 Counter 类型的内置装饰器?我面临的问题是 Counter.inc() 不是可调用的,不像 Gauge.time() 或 Summary.time()
我最近遇到了类似的问题,我通过以下方式解决了(因为我不能说这是正确的方法)(我也在寻找更简单的方法)。
PROCESS_COUNT = Counter("example:processing_count", "Number of event", ["event"])
PROCESS_TIME = Gauge("example:processing", "Time spent processing event", ["event"], unit="seconds")
# let's register how much time it take to answer on this endpoint
@PROCESS_TIME.labels("answer_json").time()
async def answer_json(request):
# let's count how many time this function has been called here
PROCESS_COUNT.labels("answer_json").inc()
# let's also register how much time this specific piece of code takes!
with ClientSession() as session, PROCESS_TIME.labels("example:update").time():
# ...
return Response(
content_type="application/json",
text=json.dumps(
# ...
),
)