0Pricing
FastAPI Backend Development Bootcamp · 강의

FastAPI 애플리케이션 디버깅

IDE 디버거와 로깅 사용을 비롯한 FastAPI 디버깅 기법을 익힙니다.

FastAPI 애플리케이션 디버깅은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is Debugging?

Welcome to debugging! As developers, we don't just write code; we also fix it. Debugging is the process of finding and resolving errors or 'bugs' in your software.

It's an essential skill that helps you understand how your code truly behaves, not just how you think it should.

  • Find Errors: Pinpoint exactly where issues occur.
  • Understand Flow: Trace execution path.
  • Inspect State: See variable values at any point.

The Simple `print()` Debug

The most basic form of debugging is using print() statements. You can sprinkle them throughout your code to see values of variables or confirm if a certain part of your code is being executed.

While quick, print() statements can clutter your output and need to be manually removed later.

Try running this simple example:

def calculate_sum(a, b):
    print(f"DEBUG: Input: a={a}, b={b}")
    result = a + b
    print(f"DEBUG: Output: result={result}")
    return result

if __name__ == "__main__":
    print("Starting calculation...")
    total = calculate_sum(5, 3)
    print(f"Final total: {total}")

Structured Logging with Python

For more robust debugging and application monitoring, Python's built-in logging module is far superior to print(). It allows you to categorize messages by severity.

Key log levels:

  • DEBUG: Detailed info, typically only for development.
  • INFO: Confirmation that things are working as expected.
  • WARNING: Something unexpected happened, but the software is still working.
  • ERROR: Serious problem, the software couldn't perform a function.
  • CRITICAL: A severe error, the program might be unable to continue.

Basic Logging in Action

With logging, you can control which messages are displayed based on their level. You can also direct logs to files, the network, or other destinations, making it much more flexible than print().

Run this example to see different log levels in action:

import logging

# Configure basic logging to show DEBUG level and above
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

def process_data(data):
    logging.debug(f"Attempting to process data: {data}")
    if not data:
        logging.warning("Received empty data for processing!")
        return []
    
    processed = [item.upper() for item in data]
    logging.info(f"Data processed successfully. Items count: {len(processed)}")
    return processed

if __name__ == "__main__":
    logging.info("Application started.")
    result1 = process_data(["apple", "banana"])
    print(f"Result 1: {result1}")
    
    result2 = process_data([])
    print(f"Result 2: {result2}")
    logging.info("Application finished.")

Integrating Logging with FastAPI

FastAPI applications, powered by Uvicorn, already use Python's logging module. When you add your own logging, you can often see it alongside Uvicorn's output.

You can create a named logger for your application to better organize your messages and control their output separately.

Here's a simple FastAPI example with integrated logging:

import logging
from fastapi import FastAPI
import uvicorn

# Get a logger for our application module
logger = logging.getLogger("my-fastapi-app")
logger.setLevel(logging.INFO) # Set default level for this logger

# Add a console handler to the logger (if not already configured by uvicorn)
# This is often handled by uvicorn itself, but good to know for custom setup
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)

app = FastAPI()

@app.get("/hello/{name}")
async def say_hello(name: str):
    logger.info(f"API call: /hello/{name}")
    if name == "error":
        logger.error("Simulating an intentional error condition!")
        return {"message": f"Hello {name}, but an error occurred.", "status": "failed"}
    logger.debug(f"Successfully processed name: {name}") # Won't show with INFO level
    return {"message": f"Hello {name}", "status": "success"}

if __name__ == "__main__":
    # In a real setup, you'd run `uvicorn main:app --reload`
    # This block allows direct execution for demonstration
    logger.info("Starting FastAPI application for demonstration...")
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")

Python's `breakpoint()` Function

Since Python 3.7, you can use the built-in breakpoint() function to pause your program's execution at a specific line.

When breakpoint() is called, Python will drop you into a debugger (often pdb, the Python Debugger). From there, you can inspect variables, step through code, and more.

This is extremely powerful for interactive debugging without needing a full IDE setup.

def calculate_discount(price, discount_percentage):
    if not (0 <= discount_percentage <= 100):
        print("Invalid discount percentage.")
        return price

    discount_amount = price * (discount_percentage / 100)
    # Uncomment the line below to pause execution here!
    # breakpoint()
    final_price = price - discount_amount
    return final_price

if __name__ == "__main__":
    print("Calculating final price...")
    item_price = 100
    discount = 15
    final = calculate_discount(item_price, discount)
    print(f"Original price: ${item_price}, Discount: {discount}%, Final price: ${final}")

Power of IDE Debuggers

Integrated Development Environment (IDE) debuggers (like those in VS Code, PyCharm, or others) are the most powerful debugging tools. They offer a visual interface to control your program's execution.

Key benefits:

  • Visual Breakpoints: Click to set/clear.
  • Step-by-Step Execution: Control flow precisely.
  • Variable Inspection: See all variable values in real-time.
  • Call Stack: Understand how you got to the current point.

Setting & Using Breakpoints

A breakpoint is a marker you place in your code that tells the debugger to pause execution when that line is reached. This lets you 'freeze' your program at a specific moment.

In most IDEs, you set a breakpoint by simply clicking in the gutter (the area to the left of the line numbers) next to the line of code you want to pause at. When you run your application in debug mode, it will stop there.

Navigating Code: Step Over, Into, Out

Once execution is paused at a breakpoint, IDE debuggers provide controls to navigate your code:

  • Step Over: Executes the current line of code and moves to the next line. If the current line calls a function, the debugger executes the entire function without stepping into it.
  • Step Into: If the current line contains a function call, the debugger will jump inside that function, allowing you to debug its internal logic.
  • Step Out: Executes the remainder of the current function and returns to the line where the function was called.

Debugging Knowledge Check

Let's test your understanding of debugging techniques.

Debugging Essentials Recap

Great job! You've explored key debugging techniques for your FastAPI applications and Python code.

  • print(): Quick & dirty for immediate checks.
  • logging module: Structured, flexible, and scalable for production and development.
  • breakpoint(): Python's built-in way to pause execution and enter a debugger.
  • IDE Debuggers: The most powerful tools for visual step-by-step execution and state inspection.

Mastering these will significantly speed up your development and problem-solving process. Keep practicing them!

자주 묻는 질문

“FastAPI 애플리케이션 디버깅” 강의는 무료인가요?

네 — “FastAPI 애플리케이션 디버깅” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“FastAPI 애플리케이션 디버깅”에서 뭘 배우나요?

IDE 디버거와 로깅 사용을 비롯한 FastAPI 디버깅 기법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“FastAPI 애플리케이션 디버깅” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Pytest를 활용한 단위 테스트
  2. FastAPI 엔드포인트 통합 테스트
  3. FastAPI 애플리케이션 디버깅
  4. FastAPI 테스트에서 종속성 모킹하기
← FastAPI Backend Development Bootcamp(으)로 돌아가기