From 7d11cd5c50b72303c90c70d0b40757a8671c17ed Mon Sep 17 00:00:00 2001 From: sergey Date: Wed, 9 Oct 2024 20:34:38 +0300 Subject: [PATCH] add log to file --- .gitignore | 3 ++- config/.env-template | 2 ++ config/config.py | 13 ++++++++++++- main.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 6cf1702..8ec3d66 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,8 @@ __pycache__ .env .vscode/ .venv/ -.log +.log/ +*.log .idea/ *.idea docker/local_redis_file/data diff --git a/config/.env-template b/config/.env-template index 971ca39..df06a2d 100644 --- a/config/.env-template +++ b/config/.env-template @@ -1,7 +1,9 @@ OAA_CFG__RUN__HOST=0.0.0.0 OAA_CFG__RUN__PORT=8000 OAA_CFG__RUN__RELOAD=True + OAA_CFG__LOG__LEVEL=30 +OAA_CFG__LOG__LEVEL_TO_FILE=30 OAA_CFG__TOKEN__ADMIN=string OAA_CFG__TOKEN__USER=string diff --git a/config/config.py b/config/config.py index 9b27842..7916e56 100644 --- a/config/config.py +++ b/config/config.py @@ -22,9 +22,10 @@ class RunConfig(BaseModel): class LogConfig(BaseModel): level: int = 30 + level_to_file: int = 30 dateformat: str = "%Y-%m-%d %H:%M:%S" format: str = ( - "[%(asctime)s.%(msecs)03d] %(module)-25s:%(lineno)4d | %(funcName)-20s| %(levelname)-8s | %(message)s" + "[%(asctime)s.%(msecs)03d] %(module)-15s:%(lineno)4d | %(funcName)-20s| %(levelname)-8s | %(message)s" ) @@ -87,8 +88,18 @@ class Settings(BaseSettings): conf = Settings() + logging.basicConfig( level=conf.log.level, datefmt=conf.log.dateformat, format=conf.log.format, ) + +file_handler = logging.FileHandler(BASE_DIR / "logfile.log") +file_handler.setLevel(conf.log.level_to_file) +file_handler.setFormatter( + logging.Formatter( + "[%(asctime)s.%(msecs)03d] %(module)s:%(lineno)4d | %(funcName)s| %(levelname)s | %(message)s" + ) +) +logging.getLogger().addHandler(file_handler) diff --git a/main.py b/main.py index 28d69d6..43910f4 100644 --- a/main.py +++ b/main.py @@ -20,7 +20,7 @@ main_app = FastAPI( lifespan=lifespan, ) - +log.warning("test") main_app.include_router(router) main_app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")