Giám sát và ghi log

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Vì sao cần giám sát và ghi log?

 

  • Không thể debug trên production
  • Trình giám sát app cần health check đơn giản
  • Ghi log các chỉ số chính theo thời gian

Phần mềm giám sát và ghi log

Triển khai AI vào môi trường sản xuất với FastAPI

Thiết lập log tùy chỉnh

 

 

  • Nạp logger lỗi của uvicorn

 

  • Thêm log tùy chỉnh khi app khởi động

 

  • Thêm log tùy chỉnh cho endpoint
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'
Triển khai AI vào môi trường sản xuất với FastAPI

Ghi log khi nạp model

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()
Triển khai AI vào môi trường sản xuất với FastAPI

Ghi log thời gian xử lý với middleware

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/
Triển khai AI vào môi trường sản xuất với FastAPI

Đặt mức độ logging

 

Các mức logging trong Python

uvicorn main:app --log-level debug
Triển khai AI vào môi trường sản xuất với FastAPI

Giám sát

 

from fastapi import FastAPI

app = FastAPI()

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

 

 

 

  • "Tôi ổn!"
Triển khai AI vào môi trường sản xuất với FastAPI

Chia sẻ tham số model qua giám sát

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}

 

 

 

 

 

  • "Tôi ổn!"
  • "Đây là vài thông tin thú vị về tôi!"
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...