# Logging an API

A server's code reports what it does through Python's logging module instead of print, with a logger per module, levels from DEBUG to ERROR, a format with the time and level, one line for every request written by a middleware, and a logging.Filter that keeps passwords and tokens out of every line.

Journeyman · FastAPI · REST API · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Log with the logging module, with a logger per module, levels from DEBUG to ERROR and a format with the time and level, instead of print
- Log one line for every request with a middleware, and keep passwords and tokens out of the logs with a logging.Filter

## Key takeaways

- On a server nobody watches the terminal, so print's lines have no time, no level and no way to be turned down without changing the code.
- logging.getLogger(__name__) gives each module its own logger, and its lines carry a level, DEBUG, INFO, WARNING or ERROR, so a setting decides how much is written.
- A middleware wraps every request, so one function can log each request's method, path, status code and time.
- A password, a token or a secret never belongs in a log. Log the path without its query string, and add a logging.Filter to the handler as a safety net.

A rider says the app showed no buses at 9 p.m. last night. You weren't watching, and you can't ask the server what happened, unless it wrote it down as it went. That written record is the server's **log**, and on any job it's the first place you look when something goes wrong.

The Campus Shuttle API has been reporting what it does with `print`, the way you've debugged scripts so far.

## Why print isn't enough on a server

Here's what the sign-in route prints when Ana, a driver, signs in. The second line is a teammate's, added while hunting a bug and never taken out:

```text
Sign-in for ana
DEBUG form: username=ana password=correct-horse-staple
```

On your laptop that's fine. On a host, it's a problem:

- **No time and no place.** A line from last night doesn't say when it happened or which file wrote it.
- **No volume knob.** The debugging line can't be turned off on the host without changing the code and deploying again.
- **A leak.** Ana's password now sits in the host's log, readable by anyone who can open it, and kept for weeks.

## Loggers and levels

Python's standard library has the tool for this: the **logging module**. Each file asks for its own **logger**, named after the file:

```python
import logging

logging.basicConfig(level="INFO", format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("routers.routes")

logger.debug("Looking up route %s", "night-owl")
logger.info("Route %s has %d stops", "night-owl", 4)
logger.warning("Route %s has no buses after %s", "gold-line", "22:45")
logger.error("No arrival times for stop %s", "stadium")
```

In a real file you write `logging.getLogger(__name__)`: `__name__` (read "dunder name") is the module's own name, `routers.routes` in `routers/routes.py`. Run it, and the terminal shows:

```text
2026-11-17 14:10:11,790 INFO routers.routes: Route night-owl has 4 stops
2026-11-17 14:10:11,790 WARNING routers.routes: Route gold-line has no buses after 22:45
2026-11-17 14:10:11,790 ERROR routers.routes: No arrival times for stop stadium
```

Each line has a **level**, from the quietest to the loudest:

| Level | For |
|---|---|
| `DEBUG` | Details you want only while hunting a bug |
| `INFO` | Normal events: started, a request answered |
| `WARNING` | Something odd that still worked |
| `ERROR` | Something failed |

`basicConfig` writes the chosen level and everything louder, so the `DEBUG` line was left out. With `level="WARNING"`, only the last two lines appear. In the shuttle API the level comes from the setting you met in *Settings Checked at Startup*: `level=settings.log_level`. The format's parts, such as `%(asctime)s` (read "percent asctime s"), are filled in for every line: the time, the level, the logger's name and the message. Inside a message, `%s` and `%d` are filled from the values after it, a piece of text and a whole number.

## One line for every request

Writing `logger.info` in every route gets old. A **middleware** is a function that runs around every request: it gets the request before the route does and the response after. One middleware can log them all:

```python
import logging
import time

from fastapi import FastAPI, Request

logging.basicConfig(level="INFO", format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)

app = FastAPI(title="Campus Shuttle")


@app.middleware("http")
async def log_requests(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    milliseconds = (time.perf_counter() - start) * 1000
    logger.info("%s %s %d %.1fms", request.method, request.url.path, response.status_code, milliseconds)
    return response
```

`@app.middleware("http")` (read "at app dot middleware http") registers it. `call_next(request)` hands the request on to the route and gives back its response. A middleware has to be written `async def`, with `await` before `call_next`: read `await` as "wait here for the route's answer"; *async and await in Plain Words*, in the next chapter, explains both. `%.1f` is a number with one decimal place.

With the routes from earlier lessons, four requests write these lines, each followed by Uvicorn's own line for it. Your times will differ:

```text
2026-11-17 14:10:20,063 INFO main: GET /routes 200 12.7ms
INFO:     127.0.0.1:43756 - "GET /routes HTTP/1.1" 200 OK
2026-11-17 14:10:20,080 INFO main: GET /routes/night-owl 200 5.5ms
INFO:     127.0.0.1:43762 - "GET /routes/night-owl HTTP/1.1" 200 OK
2026-11-17 14:10:20,112 INFO main: GET /routes/moon-loop 404 0.9ms
INFO:     127.0.0.1:43768 - "GET /routes/moon-loop HTTP/1.1" 404 Not Found
2026-11-17 14:10:20,128 INFO main: GET /routes 200 0.7ms
INFO:     127.0.0.1:43770 - "GET /routes?token=abc123 HTTP/1.1" 200 OK
```

Look at the last pair. Someone's app put a token in the query string. Your line logs `request.url.path`, the path without the query string, so the token isn't there; Uvicorn's line shows it. When your own line does the job, `uvicorn main:app --no-access-log` turns Uvicorn's off.

## Keeping secrets out of the logs

Never log a password, a token, the `Authorization` header, the JWT secret, or a whole request body or set of headers that might hold one. Write lines that name things, such as `Signed in: ana`. Still, a teammate's debugging line can slip through, so add a safety net. A **filter** is a class that sees every line before it's written; this one hides any word that starts with `password=`:

```python
import logging


class HidePasswords(logging.Filter):
    def filter(self, record):
        hidden = []
        for word in record.getMessage().split(" "):
            if word.startswith("password="):
                word = "password=***"
            hidden.append(word)
        record.msg = " ".join(hidden)
        record.args = ()
        return True


handler = logging.StreamHandler()
handler.addFilter(HidePasswords())
logging.basicConfig(level="DEBUG", format="%(levelname)s %(name)s: %(message)s", handlers=[handler])
logger = logging.getLogger("routers.auth")

logger.debug("Sign-in form: username=%s password=%s", "ana", "correct-horse-staple")
logger.info("Signed in: %s", "ana")
```

`record.getMessage()` is the line's message with its `%s` values filled in. The filter puts the hidden version back in `record.msg`, empties `record.args` (the values are already in), and returns `True` to keep the line; `False` would drop it. The **handler** is what writes lines to the terminal, and every logger's lines pass through it, so its filter covers them all. The terminal shows:

```text
DEBUG routers.auth: Sign-in form: username=ana password=***
INFO routers.auth: Signed in: ana
```

Without the filter, the first line would have been `DEBUG routers.auth: Sign-in form: username=ana password=correct-horse-staple`. Hiding part of a log line like this is called **log redaction**.

## Do it: hide passwords and tokens in the shuttle API's logs

The shuttle API's logs must never show a driver's password or a sign-in token, whichever logger writes the line.

- `record`: one log line on its way to the terminal, a `logging.LogRecord`. `record.getMessage()` gives its message with the values filled in.

**Your job:** finish the filter class `HideSecrets`, a kind of `logging.Filter`, by writing its method `filter(self, record)`:

- Go through the message's words (it's split on single spaces). A word that starts with `password=` becomes `password=***`, and a word that starts with `token=` becomes `token=***`. Every other word stays as it was.
- Put the new message, its words joined with single spaces, in `record.msg`, set `record.args` to `()`, and return `True`, so the line is still written.

Worked through: `logger.info("Sign-in form: username=%s password=%s", "ana", "correct-horse-staple")` is written as `Sign-in form: username=ana password=***`.

Practiced live on the lesson page: write the Python right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

Logs with a time, a level and one line per request let you answer "what happened last night?" in a minute, and a filter on the handler means a stray debugging line never turns that log into a list of passwords.

## Key terms

- [logging Module](https://www.ask-codey.com/glossary/logging-module)
- [Logging Levels](https://www.ask-codey.com/glossary/logging-levels)
- [Middleware](https://www.ask-codey.com/glossary/middleware)
- [Log Redaction](https://www.ask-codey.com/glossary/log-redaction)

## Related

- [Settings Checked at Startup](https://www.ask-codey.com/lessons/fastapi-pro-settings)
- [Startup, Shutdown and a Health Check](https://www.ask-codey.com/lessons/fastapi-pro-lifespan-and-health)
- [Keeping Secrets Out of Your Code](https://www.ask-codey.com/lessons/fastapi-security-secrets)

Source: https://www.ask-codey.com/lessons/fastapi-pro-logging
