0
0
FastAPIframework~5 mins

Logging errors in FastAPI

Choose your learning style9 modes available
Introduction

Logging errors helps you find and fix problems in your FastAPI app. It keeps a record of what went wrong.

When your FastAPI app crashes or behaves unexpectedly.
When you want to track errors users encounter.
When debugging issues during development or after deployment.
When you want to keep a history of errors for later review.
Syntax
FastAPI
import logging

logger = logging.getLogger("myapp")

try:
    # code that may fail
    pass
except Exception as e:
    logger.error("An error occurred", exc_info=True)

Use logger.error() to log error messages.

Set exc_info=True to include the error details and stack trace.

Examples
Logs a division by zero error with details.
FastAPI
import logging

logger = logging.getLogger("myapp")

try:
    1 / 0
except Exception as e:
    logger.error("Division by zero error", exc_info=True)
Logs a file error without stack trace.
FastAPI
import logging

logger = logging.getLogger("myapp")

try:
    open("missing_file.txt")
except Exception as e:
    logger.error(f"File error: {e}")
Sample Program

This FastAPI app has a /divide endpoint that divides two numbers. If division by zero happens, it logs the error with details and returns a friendly message.

FastAPI
from fastapi import FastAPI
import logging

app = FastAPI()
logger = logging.getLogger("uvicorn.error")

@app.get("/divide")
async def divide(a: int, b: int):
    try:
        result = a / b
        return {"result": result}
    except Exception as e:
        logger.error("Error in divide endpoint", exc_info=True)
        return {"error": "Cannot divide by zero"}
OutputSuccess
Important Notes

FastAPI uses uvicorn as the default server, which has its own logger named uvicorn.error. Use it to integrate with server logs.

Configure logging level and format in your app or server to see error logs clearly.

Summary

Logging errors helps track and fix problems in FastAPI apps.

Use logger.error() with exc_info=True to log error details and stack traces.

Integrate with uvicorn.error logger for consistent logging in FastAPI.