Реализовать observability для лабораторной 6
This commit is contained in:
+24
-17
@@ -1,12 +1,11 @@
|
||||
"""Сборка FastAPI приложения и подключение обязательных хранилищ."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
|
||||
from sqlalchemy import text
|
||||
|
||||
from .api import errors
|
||||
@@ -15,6 +14,8 @@ from .api.middleware import RequestContext
|
||||
from .api.routers import attachments, auth, chats, health, messages, users
|
||||
from .config import load_settings
|
||||
from .db import RedisSessionStore, create_engine, create_redis, create_session_factory
|
||||
from .observability import get_metrics, initialize_observability
|
||||
from .observability.logging import safe_extra
|
||||
from .repositories import AttachmentRepository, ChatRepository, MessageRepository, UserRepository
|
||||
from .services.attachments import AttachmentService
|
||||
from .services.chats import ChatService
|
||||
@@ -22,28 +23,23 @@ from .services.messages import MessageService
|
||||
from .services.users import UserService
|
||||
from .storage import S3Storage
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger('app')
|
||||
|
||||
DESCRIPTION = 'PostgreSQL хранит задания, RabbitMQ доставляет их worker, S3 хранит изображения.'
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
logging.basicConfig(
|
||||
level=os.getenv('LOG_LEVEL', 'info').upper(),
|
||||
stream=sys.stdout,
|
||||
format='%(asctime)s %(levelname)s %(name)s %(message)s',
|
||||
force=True,
|
||||
)
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
configure_logging()
|
||||
telemetry = initialize_observability('messenger-api')
|
||||
get_metrics()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI):
|
||||
application.state.ready = False
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
SQLAlchemyInstrumentor().instrument(engine=engine.sync_engine)
|
||||
redis = create_redis(settings.redis_url)
|
||||
storage = S3Storage(
|
||||
endpoint=settings.s3_endpoint,
|
||||
@@ -80,17 +76,24 @@ def create_app() -> FastAPI:
|
||||
application.state.redis = redis
|
||||
application.state.storage = storage
|
||||
application.state.ready = True
|
||||
logger.info('startup storage=postgres+s3 redis_sessions=true async_attachments=true')
|
||||
logger.info(
|
||||
'application started',
|
||||
extra=safe_extra(
|
||||
'api.startup', storage='postgres+s3', redis_sessions=True,
|
||||
async_attachments=True,
|
||||
),
|
||||
)
|
||||
yield
|
||||
finally:
|
||||
application.state.ready = False
|
||||
await redis.aclose()
|
||||
await engine.dispose()
|
||||
logger.info('shutdown complete')
|
||||
logger.info('application stopped', extra=safe_extra('api.shutdown'))
|
||||
telemetry.shutdown()
|
||||
|
||||
api = FastAPI(
|
||||
title='MTUSI Messenger. LR 5',
|
||||
version='1.5.0',
|
||||
title='MTUSI Messenger. LR 6',
|
||||
version='1.6.0',
|
||||
description=DESCRIPTION,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
@@ -107,6 +110,10 @@ def create_app() -> FastAPI:
|
||||
attachments.router,
|
||||
):
|
||||
api.include_router(router)
|
||||
FastAPIInstrumentor.instrument_app(
|
||||
api,
|
||||
excluded_urls='/health/live,/health/ready',
|
||||
)
|
||||
return api
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user