How to use logging in pydantic/fast API

5.8k views Asked by At

I am using fast API for creating an API and want to use logging to create csv logs. The API code looks like below:

@app.post("/path")
async def return_something(header: header, body: body):
    ...
    logger.info('....')
    return something

Pydantic models are defined like this:

class header(BaseModel):
    field1: str
    field2: list

I am using logger like this

from logger import ApplicationLogger
logger = ApplicationLogger()

The question is how can I use the existing longing to log pydantic errors for field verification?

2

There are 2 answers

0
mustafasencer On

Depending on you use case, you could utilize below implementations. Both implement a middleware exception_handler for the purpose of capturing a ValidationError or RequestValidationError. You could log whatever you need within your middleware as precised below. For more information you could check these Github issues (https://github.com/tiangolo/fastapi/issues/1486, https://github.com/tiangolo/fastapi/pull/853)

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc: Exception):
    """LOG HERE"""
    return PlainTextResponse(str(exc), status_code=400)

or

app = FastAPI()

async def http422_error_handler(
    _: Request, exc: Union[RequestValidationError, ValidationError]) -> JSONResponse:
    """LOG HERE"""
    return JSONResponse(
        {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY
    )

app.add_exception_handler(ValidationError, http422_error_handler)
app.add_exception_handler(RequestValidationError, http422_error_handler)
0
Zaffer On

Pydantic will automatically log errors to your terminal with the validation is not correct.

You can also log the schema like this:

logger.info(f"header schema: {header}")