Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
Python Logging con loguru- parámetros de solicitud de registro en la aplicación Fastapi

Tengo una aplicación fastapi y quiero registrar cada solicitud realizada en ella. Estoy tratando de usar loguru y uvicorn para esto, pero no sé cómo imprimir los encabezados y los parámetros de solicitud (si los hay) asociados con cada solicitud.

Quiero algo como esto:

 INFO 2020-08-13 13:36:33.494 uvicorn.protocols.http.h11_impl:send - 127.0.0.1:52660 - "GET /url1/url2/ HTTP/1.1" 400 params={"some": value, "some1":value}

Hay alguna manera ? Gracias por su ayuda.

Aquí algunos enlaces:

loguru uvicornio fastapi

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Podría usar middleware para registrar cada solicitud:

 import sys import uvicorn from fastapi import FastAPI, Request from loguru import logger from starlette.routing import Match logger.remove() logger.add(sys.stdout, colorize=True, format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>") app = FastAPI() @app.middleware("http") async def log_middle(request: Request, call_next): logger.debug(f"{request.method} {request.url}") routes = request.app.router.routes logger.debug("Params:") for route in routes: match, scope = route.matches(request) if match == Match.FULL: for name, value in scope["path_params"].items(): logger.debug(f"\t{name}: {value}") logger.debug("Headers:") for name, value in request.headers.items(): logger.debug(f"\t{name}: {value}") response = await call_next(request) return response @app.get("/{param1}/{param2}") async def path_operation(param1: str, param2: str): return {'param1': param1, 'param2': param2} if __name__ == "__main__": uvicorn.run("app:app", host="localhost", port=8001)

ACTUALIZACIÓN: también se podría usar la dependencia en el nivel del enrutador (gracias a @lsabi en los comentarios a continuación):

 import sys import uvicorn from fastapi import FastAPI, Request, APIRouter, Depends from loguru import logger from starlette.routing import Match logger.remove() logger.add(sys.stdout, colorize=True, format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>") app = FastAPI() router = APIRouter() async def logging_dependency(request: Request): logger.debug(f"{request.method} {request.url}") logger.debug("Params:") for name, value in request.path_params.items(): logger.debug(f"\t{name}: {value}") logger.debug("Headers:") for name, value in request.headers.items(): logger.debug(f"\t{name}: {value}") @router.get("/{param1}/{param2}") async def path_operation(param1: str, param2: str): return {'param1': param1, 'param2': param2} app.include_router(router, dependencies=[Depends(logging_dependency)]) if __name__ == "__main__": uvicorn.run("app:app", host="localhost", port=8001)

curl http://localhost:8001/admin/home

Producción:

 16:06:43 | DEBUG | GET http://localhost:8001/admin/home 16:06:43 | DEBUG | Params: 16:06:43 | DEBUG | param1: admin 16:06:43 | DEBUG | param2: home 16:06:43 | DEBUG | Headers: 16:06:43 | DEBUG | host: localhost:8001 16:06:43 | DEBUG | user-agent: curl/7.64.0 16:06:43 | DEBUG | accept: */*
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!