Bird
Raised Fist0
FastAPIframework~10 mins

Logging errors in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Logging errors
Start FastAPI app
Receive request
Process request
Error occurs?
NoSend response
Yes
Log error details
Send error response
Wait for next request
This flow shows how FastAPI handles a request, logs errors if they happen, and sends responses.
Execution Sample
FastAPI
from fastapi import FastAPI, Request
import logging
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(Exception)
async def log_exceptions(request: Request, exc: Exception):
    logging.error(f"Error on {request.url}: {exc}")
    return JSONResponse(status_code=500, content={"detail": "Internal Server Error"})
This code sets up FastAPI to catch all exceptions, log the error with request info, and return a simple error message.
Execution Table
StepActionInput/ConditionLogging OutputResponse Sent
1Start FastAPI appN/ANo logs yetN/A
2Receive requestGET /items/1No logs yetN/A
3Process requestCode runs normallyNo logs yet200 OK with item data
4Receive requestGET /items/999 (nonexistent)No logs yetN/A
5Process requestError: Item not foundError on http://localhost/items/999: Item not found500 Internal Server Error
6Send error responseAfter logging errorError logged{"detail": "Internal Server Error"}
7Wait for next requestN/ALogs savedN/A
💡 Execution stops waiting for next request after sending response.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
request.urlN/Ahttp://localhost/items/1http://localhost/items/999http://localhost/items/999
excN/AN/AItem not foundItem not found
logging outputEmptyEmptyError on http://localhost/items/999: Item not foundError on http://localhost/items/999: Item not found
Key Moments - 2 Insights
Why do we see no logs when the request succeeds?
Because logging.error is only called when an exception occurs, as shown in step 3 vs step 5 in the execution_table.
What does the exception handler catch?
It catches all exceptions during request processing, logs them, and returns a generic error response, as seen in steps 5 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is logged?
ANo logs yet
BError on http://localhost/items/999: Item not found
C200 OK with item data
DInternal Server Error
💡 Hint
Check the Logging Output column at step 5 in the execution_table.
At which step does the app send a 500 Internal Server Error response?
AStep 3
BStep 2
CStep 6
DStep 1
💡 Hint
Look at the Response Sent column for the 500 error in the execution_table.
If no exception occurs, what will the logging output be after processing the request?
ANo logs yet
BError on request URL
CError logged
DInternal Server Error
💡 Hint
Refer to step 3 in the execution_table where the request succeeds without error.
Concept Snapshot
FastAPI error logging:
- Use @app.exception_handler(Exception) to catch errors
- Log error details with logging.error()
- Return a generic error response
- Only logs errors when exceptions occur
- Normal requests do not produce error logs
Full Transcript
This visual execution shows how FastAPI handles requests and logs errors. When a request comes in, the app processes it. If no error happens, it sends a normal response without logging. If an error occurs, the exception handler logs the error with the request URL and exception message. Then it sends a 500 Internal Server Error response with a simple JSON message. Variables like request.url and exc hold the request info and error details. The logging output updates only when an error happens. This helps developers see what went wrong while keeping normal requests quiet.

Practice

(1/5)
1. What is the main purpose of using logger.error() with exc_info=True in a FastAPI application?
easy
A. To send an email notification when an error occurs
B. To log detailed error information including the stack trace
C. To automatically restart the FastAPI server on errors
D. To disable error logging temporarily

Solution

  1. Step 1: Understand the role of logger.error()

    This method logs error messages in the application logs.
  2. Step 2: Explain the effect of exc_info=True

    This argument adds the full exception traceback to the log, helping with debugging.
  3. Final Answer:

    To log detailed error information including the stack trace -> Option B
  4. Quick Check:

    Logging errors with traceback = A [OK]
Hint: Remember: exc_info=True shows full error details [OK]
Common Mistakes:
  • Thinking logger.error() restarts the server
  • Confusing error logging with notifications
  • Assuming exc_info=True disables logging
2. Which of the following is the correct way to log an error with exception info in FastAPI using Python's logging module?
easy
A. logger.error("Error occurred")
B. logger.error(exc_info=True)
C. logger.error("Error occurred", exception=True)
D. logger.error("Error occurred", exc_info=True)

Solution

  1. Step 1: Review the logging.error() method signature

    The method accepts a message string and optional keyword arguments like exc_info.
  2. Step 2: Identify the correct usage to include exception info

    Using exc_info=True includes the traceback in the log output.
  3. Final Answer:

    logger.error("Error occurred", exc_info=True) -> Option D
  4. Quick Check:

    Use exc_info=True to log exceptions [OK]
Hint: Use exc_info=True inside logger.error() for full error trace [OK]
Common Mistakes:
  • Omitting exc_info argument
  • Passing exc_info as a positional argument
  • Using non-existent argument 'exception=True'
3. Given this FastAPI error logging code snippet, what will be the output in the logs?
try:
    1 / 0
except Exception as e:
    logger.error("Division failed", exc_info=True)
medium
A. Logs only the message 'Division failed' without error details
B. Raises a ZeroDivisionError and stops the program
C. Logs the message 'Division failed' with a ZeroDivisionError traceback
D. Logs nothing because exception is caught

Solution

  1. Step 1: Analyze the try-except block

    The code attempts division by zero, which raises ZeroDivisionError caught by except.
  2. Step 2: Understand logger.error with exc_info=True

    It logs the message plus the full traceback of the caught exception.
  3. Final Answer:

    Logs the message 'Division failed' with a ZeroDivisionError traceback -> Option C
  4. Quick Check:

    exc_info=True logs error trace [OK]
Hint: exc_info=True logs full error trace, not just message [OK]
Common Mistakes:
  • Thinking the error stops the program
  • Assuming no traceback is logged
  • Believing the log is empty on exception
4. You wrote this FastAPI error logging code but no error details appear in logs:
try:
    open('missing_file.txt')
except Exception:
    logger.error("File open failed")
What is the main fix to log the error details?
medium
A. Add exc_info=True to logger.error call
B. Change except Exception to except FileNotFoundError
C. Use logger.info instead of logger.error
D. Remove the try-except block

Solution

  1. Step 1: Identify missing error detail logging

    The current logger.error call logs only the message without exception info.
  2. Step 2: Add exc_info=True to include traceback

    Passing exc_info=True logs the full exception details automatically.
  3. Final Answer:

    Add exc_info=True to logger.error call -> Option A
  4. Quick Check:

    Include exc_info=True to log error details [OK]
Hint: Always add exc_info=True to log exceptions fully [OK]
Common Mistakes:
  • Changing exception type without logging fix
  • Using logger.info which is lower severity
  • Removing try-except causing crashes
5. You want to log errors in a FastAPI app only when an exception occurs, including the traceback, but avoid logging if no error happens. Which code snippet correctly implements this?
hard
A. try: risky_operation() except Exception as e: logger.error("Operation failed", exc_info=True)
B. logger.error("Operation failed", exc_info=True) risky_operation()
C. try: risky_operation() except Exception: logger.error("Operation failed")
D. try: risky_operation() except Exception as e: logger.error("Operation failed")

Solution

  1. Step 1: Ensure error logging happens only on exceptions

    Logging must be inside except block to avoid logging when no error occurs.
  2. Step 2: Include exc_info=True to log traceback

    Passing exc_info=True ensures full error details are logged.
  3. Final Answer:

    try: risky_operation() except Exception as e: logger.error("Operation failed", exc_info=True) -> Option A
  4. Quick Check:

    Log errors with traceback only on exceptions [OK]
Hint: Log errors inside except with exc_info=True [OK]
Common Mistakes:
  • Logging errors outside try-except block
  • Omitting exc_info=True losing traceback
  • Logging without exception object