Request Logging Middleware
Exit

Request Logging Middleware

Add middleware that logs every request with its method, path, status, and duration

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why log requests

When your API is running, you have no visibility into what is happening unless you add logging. If a user reports a slow response or an error, you need to know which endpoint was hit, what status code was returned, and how long it took.

A logging middleware prints this information for every request automatically. You do not need to add logging code to each endpoint individually.

Measuring duration

To measure how long a request takes, record the time before calling the endpoint and subtract it from the time after. Python's time.time() returns the current time in seconds. Multiplying the difference by 1000 converts it to milliseconds.

start = time.time()
# ... do work ...
duration = (time.time() - start) * 1000

The middleware pattern

Your middleware will:

  1. Record the start time
  2. Call call_next(request) to run the endpoint
  3. Calculate the duration
  4. Print the method, path, status code, and duration
  5. Return the response

Instructions

Add a request logging middleware to your API.

  1. Add import time to the top of the file, after the existing imports.
  2. Add the @app.middleware("http") decorator after the load_expenses() call and before the first endpoint.
  3. Define an async function called log_requests that takes request and call_next as parameters.
  4. Inside the function, record the start time with start = time.time().
  5. Call response = await call_next(request) — this passes the request to the next handler (your endpoint) and waits for the response.
  6. Calculate the duration with duration = (time.time() - start) * 1000.
  7. Print the log line: f"{request.method} {request.url.path} {response.status_code} {duration:.1f}ms".
  8. Return response.