監控與記錄

使用 FastAPI 將 AI 佈署到生產環境

Matt Eckerle

Software and Data Engineering Leader

為什麼要監控與記錄?

 

  • 無法在正式環境除錯
  • 監控程式需簡易健檢
  • 長期記錄關鍵指標

監控與記錄軟體

使用 FastAPI 將 AI 佈署到生產環境

設定自訂記錄

 

 

  • 載入 uvicorn 錯誤記錄器

 

  • 在應用啟動時加入自訂記錄

 

  • 在端點加入自訂記錄
from fastapi import FastAPI
import logging

logger = logging.getLogger(
    'uvicorn.error'
)

app = FastAPI() logger.info("App is running!")
@app.get('/') async def main(): logger.debug('GET /') return 'ok'
使用 FastAPI 將 AI 佈署到生產環境

載入模型時寫入記錄

from fastapi import FastAPI
import logging
import joblib 

logger = logging.getLogger('uvicorn.error')

model = joblib.load('penguin_classifier.pkl') logger.info("Penguin classifier loaded successfully.") app = FastAPI()
使用 FastAPI 將 AI 佈署到生產環境

用中介層記錄處理時間

from fastapi import FastAPI, Request
import logging
import time
logger = logging.getLogger('uvicorn.error')
app = FastAPI()

@app.middleware("http")
async def log_process_time(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    logger.info(f"Process time was {process_time} seconds.")
    return response
1 https://fastapi.tiangolo.com/tutorial/middleware/
使用 FastAPI 將 AI 佈署到生產環境

設定記錄層級

 

Python 記錄層級

uvicorn main:app --log-level debug
使用 FastAPI 將 AI 佈署到生產環境

監控

 

from fastapi import FastAPI

app = FastAPI()

@app.get("/health") async def get_health(): return {"status": "OK"}

 

 

 

  • 「I'm ok!」
使用 FastAPI 將 AI 佈署到生產環境

與監控分享模型參數

from fastapi import FastAPI
import joblib

model = joblib.load(
    'penguin_classifier.pkl'
)
app = FastAPI()

@app.get("/health") async def get_health(): params = model.get_params() return {"status": "OK", "params": params}

 

 

 

 

 

  • 「I'm ok!」
  • 「Here are some fun facts about me!」
使用 FastAPI 將 AI 佈署到生產環境

一起來練習吧!

使用 FastAPI 將 AI 佈署到生產環境

Preparing Video For Download...