To log 422 validation errors to the console in FastAPI, you can create a custom exception handler. Here's how:
python
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import logging
app = FastAPI()
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
# Log the validation errors to console
logger.error(f"Validation error for {request.method} {request.url}")
logger.error(f"Request body: {await request.body()}")
logger.error(f"Validation errors: {exc.errors()}")
# Return the standard 422 response
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": exc.errors()},
)
For more detailed logging with formatted output:
python
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
# Get request body
body = await request.body()
# Format the error message
error_msg = f"\n{'='*50}\n"
error_msg += f"422 Validation Error\n"
error_msg += f"{'='*50}\n"
error_msg += f"Endpoint: {request.method} {request.url.path}\n"
error_msg += f"Client: {request.client.host if request.client else 'Unknown'}\n"
if body:
error_msg += f"Request body: {body.decode('utf-8')}\n"
error_msg += "\nValidation errors:\n"
for error in exc.errors():
loc = " -> ".join(str(l) for l in error['loc'])
error_msg += f" - Field: {loc}\n"
error_msg += f" Error: {error['msg']}\n"
error_msg += f" Type: {error['type']}\n"
error_msg += f"{'='*50}\n"
# Log to console
logger.error(error_msg)
# Return the standard 422 response
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": exc.errors()},
)
Example usage with a test endpoint:
python
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
email: str
@app.post("/users/")
async def create_user(user: User):
return {"message": f"User {user.name} created"}
When you send an invalid request, you'll see detailed error information in your console:
code
==================================================
422 Validation Error
==================================================
Endpoint: POST /users/
Client: 127.0.0.1
Request body: {"name": "John", "age": "not_a_number", "email": "invalid"}
Validation errors:
- Field: body -> age
Error: value is not a valid integer
Type: type_error.integer
==================================================
This approach gives you visibility into validation errors while maintaining FastAPI's standard error responses to clients.
User
output it in one line
Assistant
Here's how to log 422 validation errors in a single line:
python
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import logging
app = FastAPI()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
# Create a one-line error message
errors = "; ".join([f"{'.'.join(str(l) for l in e['loc'])}: {e['msg']}" for e in exc.errors()])
body = (await request.body()).decode('utf-8')
# Log in one line
logger.error(f"422 Error - {request.method} {request.url.path} - Body: {body} - Errors: {errors}")
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": exc.errors()},
)
For even more compact output without the request body:
python
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = "; ".join([f"{'.'.join(str(l) for l in e['loc'])}: {e['msg']}" for e in exc.errors()])
logger.error(f"422: {request.method} {request.url.path} - {errors}")
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": exc.errors()},
)
Example output:
code
ERROR:__main__:422: POST /users/ - body.age: value is not a valid integer; body.email: value is not a valid email address