Bird
0
0

You want to initialize a logging system on startup and properly close it on shutdown in FastAPI. Which code snippet correctly implements this lifecycle management?

hard📝 lifecycle Q8 of 15
FastAPI - Middleware and Hooks
You want to initialize a logging system on startup and properly close it on shutdown in FastAPI. Which code snippet correctly implements this lifecycle management?
AUse <code>@app.on_event("startup")</code> to configure logging and <code>@app.on_event("shutdown")</code> to flush and close handlers
BConfigure logging inside route handlers and close it in middleware
CInitialize logging globally without event handlers and rely on garbage collection
DUse <code>@app.middleware("http")</code> to start and stop logging
Step-by-Step Solution
Solution:
  1. Step 1: Understand lifecycle events

    Startup and shutdown events are designed for initializing and cleaning up resources.
  2. Step 2: Apply to logging

    Logging setup should be done once at startup; flushing and closing handlers should happen at shutdown.
  3. Step 3: Eliminate incorrect options

    Configuring logging inside routes or middleware is inefficient; relying on garbage collection is unreliable.
  4. Final Answer:

    Use @app.on_event("startup") to configure logging and @app.on_event("shutdown") to flush and close handlers -> Option A
  5. Quick Check:

    Use startup/shutdown events for resource management [OK]
Quick Trick: Manage resources in startup and shutdown events [OK]
Common Mistakes:
MISTAKES
  • Initializing resources per request
  • Not closing resources explicitly
  • Using middleware for startup/shutdown logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes