如何实现模型服务的日志和分布式追踪?
中等
答题要点
# 结构化日志
import logging
import json
class JSONFormatter(logging.Formatter):
def format(self, record):
log_obj = {
'timestamp': self.formatTime(record),
'level': record.levelname,
'message': record.getMessage(),
'request_id': getattr(record, 'request_id', None),
'model_version': getattr(record, 'model_version', None),
}
return json.dumps(log_obj)
# OpenTelemetry分布式追踪
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
tracer = trace.get_tracer(__name__)
@app.post("/predict")
async def predict(request: PredictRequest):
with tracer.start_as_current_span("predict") as span:
span.set_attribute("model.version", "v1")
span.set_attribute("input.size", len(request.features))
with tracer.start_as_current_span("preprocess"):
features = preprocess(request.features)
with tracer.start_as_current_span("inference"):
prediction = model.predict(features)
return {"prediction": prediction}
FastAPIInstrumentor.instrument_app(app)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题