From e847a9cb8f0a079d7dbc4fe7608f164d0ab929a9 Mon Sep 17 00:00:00 2001 From: sparrowsurya Date: Sun, 25 Aug 2024 00:04:06 +0530 Subject: [PATCH] removed dep fatapi-cli and added logging --- README.md | 7 +------ api/background_tasks.py | 12 ++++++++++-- api/config.py | 5 ++++- api/main.py | 7 +++++++ log_config.yaml | 34 ++++++++++++++++++++++++++++++++++ pyproject.toml | 1 - requirements.txt | 1 - 7 files changed, 56 insertions(+), 11 deletions(-) create mode 100644 log_config.yaml diff --git a/README.md b/README.md index e72c813..cd6a1de 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,6 @@ A fastapi service for code sharing. ![os](https://img.shields.io/badge/os-Linux-blue) -## TODOS -* logger -* deployment - - ## Run 0. Download this project ```sh @@ -37,5 +32,5 @@ python3 -m pip install -r requirements.txt 3. Run the api ```sh -fastapi dev api/main.py +uvicrn api.main:app --log-config=log_config.yaml ``` diff --git a/api/background_tasks.py b/api/background_tasks.py index ef8b8c9..1296d48 100644 --- a/api/background_tasks.py +++ b/api/background_tasks.py @@ -1,15 +1,23 @@ import asyncio +import logging from sqlalchemy.orm import Session from . import crud +logger = logging.getLogger(__name__) + + async def delete_expired_paste_task(interval: float, db: Session): - while True: + run = 1 + logger.info(f"Task started: delete-expired-paste after each {interval}s.") + while run: try: await asyncio.sleep(interval) except asyncio.CancelledError: - return + run = False else: crud.delete_expired_pastes(db) + + logger.info("Task ended: delete-expired-paste.") \ No newline at end of file diff --git a/api/config.py b/api/config.py index bb5712d..c8ff4bd 100644 --- a/api/config.py +++ b/api/config.py @@ -4,6 +4,9 @@ from functools import lru_cache +logger = logging.getLogger(__name__) + + class Settings(BaseSettings): """Settings for the application.""" @@ -19,5 +22,5 @@ class Settings(BaseSettings): def get_settings() -> Settings: """Get the application settings.""" settings = Settings() - logging.info(f"Loading settings for {settings.env_name}") + logger.info(f"Loading settings for {settings.env_name}") return settings diff --git a/api/main.py b/api/main.py index b16c161..566a005 100644 --- a/api/main.py +++ b/api/main.py @@ -1,4 +1,5 @@ import asyncio +import logging from contextlib import asynccontextmanager from fastapi import Depends, FastAPI, HTTPException, Request @@ -10,13 +11,18 @@ from .background_tasks import delete_expired_paste_task +logger = logging.getLogger(__name__) + + @asynccontextmanager async def lifespan(app: FastAPI): + logger.info("Application lifespan started!") interval = float(get_settings().interval) db = SessionLocal() asyncio.create_task(delete_expired_paste_task(interval, db)) yield db.close() + logger.info("Application lifespan ended!") app = FastAPI(lifespan=lifespan) @@ -33,6 +39,7 @@ def create_paste(paste: schemas.Paste, db: Session = Depends(get_db)): try: db_paste = crud.create_db_paste(db, paste) except RuntimeError as error: + logger.exception(error) raise HTTPException(status_code=500, detail=str(error)) url = get_settings().base_url + f"/{db_paste.key}" diff --git a/log_config.yaml b/log_config.yaml new file mode 100644 index 0000000..711aeef --- /dev/null +++ b/log_config.yaml @@ -0,0 +1,34 @@ +version: 1 +disable_existing_loggers: False +formatters: + default: + # "()": uvicorn.logging.DefaultFormatter + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + access: + # "()": uvicorn.logging.AccessFormatter + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' +handlers: + default: + formatter: default + class: logging.StreamHandler + stream: ext://sys.stderr + access: + formatter: access + class: logging.StreamHandler + stream: ext://sys.stdout +loggers: + uvicorn.error: + level: INFO + handlers: + - default + propagate: no + uvicorn.access: + level: INFO + handlers: + - access + propagate: no +root: + level: DEBUG + handlers: + - default + propagate: no \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 59fd439..675c4d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,6 @@ dependencies = [ "dnspython==2.6.1", "email_validator==2.2.0", "fastapi==0.112.0", - "fastapi-cli==0.0.5", "greenlet==3.0.3", "h11==0.14.0", "httpcore==1.0.5", diff --git a/requirements.txt b/requirements.txt index 604d8ba..4b1d1d2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,6 @@ click==8.1.7 dnspython==2.6.1 email_validator==2.2.0 fastapi==0.112.0 -fastapi-cli==0.0.5 greenlet==3.0.3 h11==0.14.0 httpcore==1.0.5