From b6af8d438a23fdf8a71797e4da3c8c9896fd8dd8 Mon Sep 17 00:00:00 2001 From: David Pomerenke <46022183+davidpomerenke@users.noreply.github.com> Date: Wed, 10 Apr 2024 19:10:17 +0000 Subject: [PATCH] refactor(api): refactor logging to newer fastapi command see https://fastapi.tiangolo.com/advanced/events/ --- backend-python/media_impact_monitor/api.py | 24 +++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/backend-python/media_impact_monitor/api.py b/backend-python/media_impact_monitor/api.py index 184bb110..8be7da9e 100644 --- a/backend-python/media_impact_monitor/api.py +++ b/backend-python/media_impact_monitor/api.py @@ -5,6 +5,7 @@ """ import logging +from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from joblib import hash as joblib_hash @@ -40,6 +41,17 @@ docs_url=None, ) + +@asynccontextmanager +async def app_lifespan(app: FastAPI): + logger = logging.getLogger("uvicorn.access") + console_formatter = AccessFormatter( + "{asctime} {levelprefix} {message}", style="{", use_colors=True + ) + logger.handlers[0].setFormatter(console_formatter) + yield + + app = FastAPI(**metadata) app.add_middleware( @@ -51,11 +63,13 @@ ) -logger = logging.getLogger("uvicorn.access") -console_formatter = AccessFormatter( - "{asctime} {levelprefix} {message}", style="{", use_colors=True -) -logger.handlers[0].setFormatter(console_formatter) +@app.on_event("startup") +async def startup_event(): + logger = logging.getLogger("uvicorn.access") + console_formatter = AccessFormatter( + "{asctime} {levelprefix} {message}", style="{", use_colors=True + ) + logger.handlers[0].setFormatter(console_formatter) @app.get("/", include_in_schema=False)