Created
April 18, 2020 20:18
-
-
Save philippegirard/7cdbec8036561285b5579d8d334b20ba to your computer and use it in GitHub Desktop.
fastapi logging middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from fastapi import FastAPI | |
from uicheckapp.services import EchoService | |
logging.config.fileConfig('logging.conf', disable_existing_loggers=False) | |
logger = logging.getLogger(__name__) | |
app = FastAPI() | |
@app.middleware("http") | |
async def log_requests(request: Request, call_next): | |
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6)) | |
logger.info(f"rid={idem} start request path={request.url.path}") | |
start_time = time.time() | |
response = await call_next(request) | |
process_time = (time.time() - start_time) * 1000 | |
formatted_process_time = '{0:.2f}'.format(process_time) | |
logger.info(f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}") | |
return response | |
@app.get("/") | |
async def root(): | |
logger.info("logging from the root logger") | |
EchoService.echo("hi") | |
return {"status": "alive"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx very much!