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
Logging errors in FastAPI
📖 Scenario: You are building a simple web API using FastAPI. You want to keep track of errors that happen when users call your API. Logging errors helps you find and fix problems quickly.
🎯 Goal: Create a FastAPI app that logs error messages when an exception happens in an endpoint.
📋 What You'll Learn
Create a FastAPI app instance called app
Set up a logger named logger using Python's logging module
Add a configuration to log error messages to the console
Create an endpoint /divide that divides two query parameters a and b
Catch division errors and log the error message using logger.error
Return a JSON response with the error message when division by zero occurs
💡 Why This Matters
🌍 Real World
Logging errors in web APIs helps developers quickly find and fix bugs, improving app reliability.
💼 Career
Understanding error logging is essential for backend developers and DevOps engineers to maintain healthy production systems.
Progress0 / 4 steps
1
Create FastAPI app and import logging
Import FastAPI from fastapi and logging. Create a FastAPI app instance called app.
FastAPI
Hint
Use app = FastAPI() to create the app instance.
2
Set up logger to log errors to console
Create a logger named logger using logging.getLogger(__name__). Set the logger level to logging.ERROR. Add a StreamHandler to output logs to the console.
FastAPI
Hint
Use logging.getLogger(__name__) to create the logger and logger.setLevel(logging.ERROR) to set the level.
3
Create /divide endpoint with error logging
Create a GET endpoint /divide that accepts query parameters a and b as floats. Inside the function, try to divide a by b. If a ZeroDivisionError occurs, log the error message using logger.error and return a JSON response with key error and a message "Cannot divide by zero".
FastAPI
Hint
Use try and except ZeroDivisionError as e to catch the error and log it.
4
Print a test log message
Add a line to log an error message "Test error log" using logger.error.
FastAPI
Hint
Use logger.error("Test error log") to print the test message.
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
Step 1: Understand the role of logger.error()
This method logs error messages in the application logs.
Step 2: Explain the effect of exc_info=True
This argument adds the full exception traceback to the log, helping with debugging.
Final Answer:
To log detailed error information including the stack trace -> Option B
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
Step 1: Review the logging.error() method signature
The method accepts a message string and optional keyword arguments like exc_info.
Step 2: Identify the correct usage to include exception info
Using exc_info=True includes the traceback in the log output.
Final Answer:
logger.error("Error occurred", exc_info=True) -> Option D
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?
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
Step 1: Analyze the try-except block
The code attempts division by zero, which raises ZeroDivisionError caught by except.
Step 2: Understand logger.error with exc_info=True
It logs the message plus the full traceback of the caught exception.
Final Answer:
Logs the message 'Division failed' with a ZeroDivisionError traceback -> Option C
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
Step 1: Identify missing error detail logging
The current logger.error call logs only the message without exception info.
Step 2: Add exc_info=True to include traceback
Passing exc_info=True logs the full exception details automatically.
Final Answer:
Add exc_info=True to logger.error call -> Option A
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
Step 1: Ensure error logging happens only on exceptions
Logging must be inside except block to avoid logging when no error occurs.
Step 2: Include exc_info=True to log traceback
Passing exc_info=True ensures full error details are logged.
Final Answer:
try:
risky_operation()
except Exception as e:
logger.error("Operation failed", exc_info=True) -> Option A
Quick Check:
Log errors with traceback only on exceptions [OK]
Hint: Log errors inside except with exc_info=True [OK]