---
title: "Set up FastAPI logging and handle errors without losing the traceback"
description: "FastAPI printed no info log with no setup, and only uvicorn printed the traceback of a 500 error. Here is the FastAPI logging setup, the error handlers, and LogBrew, tested on FastAPI 0.165."
canonical: "https://logbrew.co/en/guides/fastapi-logging"
last_updated: "2026-11-21"
---

# Set up FastAPI logging and handle errors without losing the traceback

FastAPI printed no `info` log with no setup, and only uvicorn printed the traceback of a 500 error. Here is the FastAPI logging setup, the error handlers, and LogBrew, tested on FastAPI 0.165.

Tested on November 21, 2026 with Python 3.13.5, FastAPI 0.165.0, uvicorn 0.54.0, logbrew-sdk 0.1.29, logbrew-fastapi 0.1.14, and logbrew CLI 0.1.96

By [Furkan Erday](https://github.com/furkanerday). Furkan Erday is the founder of LogBrew. He builds LogBrew with Claude Code and Codex every day.

Canonical: https://logbrew.co/en/guides/fastapi-logging

## What FastAPI prints with no setup, and what LogBrew gets

| Event | Printed with no setup | Issue or log in LogBrew |
| --- | --- | --- |
| `logger.debug()` | Dropped | Dropped at `INFO` |
| `logger.info()` | Dropped | `info` log |
| `logger.warning()` | Message only | `warning` log |
| `ValueError` in a route | Traceback from uvicorn | Issue |
| Path value not a number, 422 | Access line only | Span, no issue |
| `HTTPException`, 404 | Access line only | Span, no issue |

6 events in FastAPI 0.165.0 under uvicorn 0.54.0, then the same with `basicConfig()` and logbrew-fastapi 0.1.14.

## Log from a FastAPI app

### See what FastAPI prints with no setup

Our app has 1 logger named `taproom` and 3 routes. We started it with `uvicorn main:app`. uvicorn sets up only its own loggers, so Python printed `warning` and higher as bare text, and dropped `debug` and `info`.

```bash
import logging

from fastapi import FastAPI, HTTPException

app = FastAPI()
logger = logging.getLogger("taproom")


@app.get("/taps/{tap}")
def pour(tap: str):
    logger.debug("keg pressure read")
    logger.info("tap %s opened", tap)
    logger.warning("keg below 10%")
    logger.error("keg empty")
    logger.critical("cooler offline")
    return {"tap": tap}


@app.get("/kegs/{keg_id}")
def keg(keg_id: int):
    raise ValueError(f"keg {keg_id} is empty")


@app.get("/missing")
def missing():
    raise HTTPException(status_code=404, detail="no such tap")
```

Output

```text
keg below 10%
keg empty
cooler offline
INFO:     127.0.0.1:51421 - "GET /taps/ipa HTTP/1.1" 200 OK
```

### Call basicConfig() before you create the app

`logging.basicConfig()` gives the root logger a level and a format. The `taproom` lines now show their level, and `info` appears. uvicorn keeps its own format.

```bash
import logging
import os

from fastapi import FastAPI, HTTPException

logging.basicConfig(
    level=os.environ.get("LOG_LEVEL", "INFO"),
    format="%(levelname)s %(name)s %(message)s",
)

app = FastAPI()
logger = logging.getLogger("taproom")
```

Output

```text
INFO taproom tap ipa opened
WARNING taproom keg below 10%
ERROR taproom keg empty
CRITICAL taproom cooler offline
INFO:     127.0.0.1:51428 - "GET /taps/ipa HTTP/1.1" 200 OK
```

### Read the level from the environment

The `basicConfig()` call above reads `LOG_LEVEL`. Start uvicorn with `LOG_LEVEL=DEBUG`, and the `debug` line appears with no code change.

```bash
LOG_LEVEL=DEBUG uvicorn main:app
```

Output

```text
DEBUG taproom keg pressure read
INFO taproom tap ipa opened
WARNING taproom keg below 10%
ERROR taproom keg empty
CRITICAL taproom cooler offline
INFO:     127.0.0.1:51442 - "GET /taps/ipa HTTP/1.1" 200 OK
```

## Handle errors in FastAPI

### See what an unhandled exception prints

The client got `Internal Server Error` with status 500. uvicorn printed `Exception in ASGI application` and the traceback. The path `/kegs/abc` returned 422 with a `detail` list, and `HTTPException` returned its `detail` with 404. Neither printed a traceback. We cut 27 frames of uvicorn, Starlette, and FastAPI.

```bash
curl localhost:8000/kegs/7
curl localhost:8000/kegs/abc
curl localhost:8000/missing
```

Output

```text
INFO:     127.0.0.1:51422 - "GET /kegs/7 HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  …
  File "main.py", line 21, in keg
    raise ValueError(f"keg {keg_id} is empty")
ValueError: keg 7 is empty
INFO:     127.0.0.1:51423 - "GET /kegs/abc HTTP/1.1" 422 Unprocessable Content
INFO:     127.0.0.1:51424 - "GET /missing HTTP/1.1" 404 Not Found
```

### Add an exception handler for Exception

The handler logs the error and returns your own JSON, and the client got `{"error":"internal"}`. uvicorn still printed the traceback, because Starlette raises the exception again after it sends your response. So the traceback appeared 2 times.

```bash
from fastapi import Request
from fastapi.responses import JSONResponse


@app.exception_handler(Exception)
async def on_error(request: Request, exc: Exception):
    logger.exception("request failed")
    return JSONResponse({"error": "internal"}, status_code=500)
```

Output

```text
ERROR taproom request failed
Traceback (most recent call last):
  …
  File "main.py", line 34, in keg
    raise ValueError(f"keg {keg_id} is empty")
ValueError: keg 7 is empty
INFO:     127.0.0.1:51436 - "GET /kegs/7 HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  …
  File "main.py", line 34, in keg
    raise ValueError(f"keg {keg_id} is empty")
ValueError: keg 7 is empty
```

## Send FastAPI logs and errors to LogBrew

### Install the package

`logbrew-fastapi` installs `logbrew-sdk` too. Use a server key of your LogBrew project.

```bash
python3 -m pip install logbrew-sdk logbrew-fastapi
```

### Call init_logbrew() after you create the app

`init_logbrew()` records a span for each request and records each unhandled error as an issue. `logbrew.logging_handler` sends the records of your logger. We sent to a local LogBrew server, so our copy also passed a `transport`.

```bash
import logging
import os

from fastapi import FastAPI, HTTPException
from logbrew_fastapi import init_logbrew

logging.basicConfig(
    level=os.environ.get("LOG_LEVEL", "INFO"),
    format="%(levelname)s %(name)s %(message)s",
)

app = FastAPI()
logbrew = init_logbrew(
    app, api_key=os.environ["LOGBREW_API_KEY"], service_name="taproom"
)
logger = logging.getLogger("taproom")
logger.addHandler(logbrew.logging_handler)
```

### Read the issue and the logs back

We sent the same 4 requests again and read the project with a read key. The 500 error became 1 issue named after the route template. The 4 logs of `/taps/ipa` share 1 trace ID. The 422 and the 404 made no issue.

```bash
logbrew issues --since 1h
logbrew read logs --since 1h
```

Output

```text
Issues (1)
- b100cd3d-f932-57c7-8f23-38067f1c87d7 unresolved error priority=medium GET /kegs/{keg_id} failed occurrences=1 users=unknown last_seen=2026-11-21T06:44:18.663Z service=taproom trace=6b642297fc5d4259b1f17f2bf83b1abb assignee=unassigned [unversioned / production]
Logs (4)
- error keg empty service=taproom trace=fcc0eaf7997f4e0796c0b76e0678b455 [unversioned / production]
- warning keg below 10% service=taproom trace=fcc0eaf7997f4e0796c0b76e0678b455 [unversioned / production]
- critical cooler offline service=taproom trace=fcc0eaf7997f4e0796c0b76e0678b455 [unversioned / production]
- info tap ipa opened service=taproom trace=fcc0eaf7997f4e0796c0b76e0678b455 [unversioned / production]
```

### Check what the issue keeps

The issue keeps the exception type, the route, and 21 stack frames, but not the message. LogBrew writes `Unhandled exception` in its place.

```bash
logbrew issues --since 1h --json | jq '.[0].attributes | {
  message, exception,
  route: .metadata.routeTemplate,
  frames: (.stackFrames | length)
}'
```

Output

```text
{
  "message": "Unhandled exception",
  "exception": {
    "mechanism": {
      "handled": false,
      "type": "fastapi.middleware"
    },
    "type": "ValueError"
  },
  "route": "/kegs/{keg_id}",
  "frames": 21
}
```

### Keep the message with your exception handler

With the exception handler from above, LogBrew still recorded the issue, and the `request failed` log kept the message that the issue leaves out.

```bash
logbrew read logs --since 1h --severity error \
  --search "request failed" --json | jq '.[0] | {
  message,
  exceptionName: .attributes.metadata.exceptionName,
  exceptionMessage: .attributes.metadata.exceptionMessage
}'
```

Output

```text
{
  "message": "request failed",
  "exceptionName": "ValueError",
  "exceptionMessage": "keg 7 is empty"
}
```

## What we saw when we tested it

We ran 1 FastAPI 0.165.0 app with uvicorn 0.54.0 on Python 3.13.5, called each route with curl, and read the server output. Then we added logbrew-fastapi 0.1.14 and read what a local LogBrew server stored.

uvicorn printed the traceback of each unhandled exception, with or without a handler. Errors that FastAPI turns into a response, such as a 422 or an `HTTPException`, printed only the access line.

| Request | `status_code` | Traceback printed | Issue in LogBrew |
| --- | --- | --- | --- |
| `/kegs/7` | `500` | Yes | Yes |
| `/kegs/abc` | `422` | No | No |
| `/missing` | `404` | No | No |

## FastAPI log levels and the uvicorn output

Python has 5 levels, `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`. With no setup, the root logger drops each record below `WARNING`.

uvicorn prints its access lines and its errors in its own format, and `basicConfig()` did not change them. LogBrew keeps `warning`, `error`, and `critical` as they are, and stores `DEBUG` and `INFO` as `info`.

|  | No setup | `basicConfig()` | LogBrew |
| --- | --- | --- | --- |
| `logger.debug()` | No | With `LOG_LEVEL=DEBUG` | No |
| `logger.info()` | No | Yes | `info` |
| `logger.warning()` | Yes | Yes | `warning` |
| `logger.error()` | Yes | Yes | `error` |
| `logger.critical()` | Yes | Yes | `critical` |

## What LogBrew records

`init_logbrew()` records 1 span per request, named after the route template, such as `GET /kegs/{keg_id}`. An unhandled exception adds an issue with the exception type, the mechanism `fastapi.middleware`, `handled: false`, and the stack frames.

A log written during a request carries the trace ID of that request. The 422 and 404 requests made spans with no error.

- `init_logbrew()`
  - Issue: `GET /kegs/{keg_id} failed`
  - `exception.type`: `ValueError`
  - `mechanism`: `fastapi.middleware`
  - `handled`: `false`
  - Stack frames: 21
- `logbrew.logging_handler`
  - Message: `request failed`
  - `exceptionName`: `ValueError`
  - `exceptionMessage`: `keg 7 is empty`

## Questions people ask

### How do I set up logging in FastAPI?

Call `logging.basicConfig()` once at the top of `main.py`, then use `logging.getLogger()` in each module. With no setup, Python drops `info` and `debug`.

### How do I handle all exceptions in FastAPI?

Add `@app.exception_handler(Exception)` and return your own response. The client gets your response, and uvicorn still prints the traceback.

### Why does FastAPI return 422?

A path, query, or body value did not match its type. `/kegs/abc` failed the `keg_id: int` check, so FastAPI returned the `detail` list with status 422.

### What does Exception in ASGI application mean?

An exception left your route and no handler ended it. uvicorn logs it with the traceback, and the client gets `Internal Server Error` with status 500.

## See every FastAPI error with its route

logbrew-fastapi records each unhandled error as an issue named after its route template, and sends your logs with the trace of their request. Start on the generous free tier, no card needed.

[Start Free](https://logbrew.co/en)

## Sources

- [FastAPI docs, Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers)
- [FastAPI docs, Use HTTPException](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)
- [fastapi/fastapi#14071](https://github.com/fastapi/fastapi/discussions/14071)

## More guides for agents, Python, Node.js, and React

- [Claude Code MCP and Codex MCP server setup](https://logbrew.co/en/guides/mcp-server-claude-code-codex)
- [Use AGENTS.md in Claude Code and Codex](https://logbrew.co/en/guides/agents-md)
- [Fix the Claude overloaded error 529 and rate limit error 429](https://logbrew.co/en/guides/claude-overloaded-rate-limit-error)
- [Set up Python logging with the right log levels and exception capture](https://logbrew.co/en/guides/python-logging)
- [Structured logging with a log format and log levels you can search by field](https://logbrew.co/en/guides/structured-logging)
- [Set up the Pino logger or Winston in Node.js and keep every error](https://logbrew.co/en/guides/node-logging)
- [Set up Django logging and keep the traceback of every 500 error](https://logbrew.co/en/guides/django-logging)
- [Add a React error boundary and log the errors it misses](https://logbrew.co/en/guides/react-error-boundary)
- [Trace ID vs span ID, decoded from a real traceparent header](https://logbrew.co/en/guides/trace-id)
- [How to fix errors and set up logs, traces, metrics & releases](https://logbrew.co/en/guides)
