FastAPI Logging

When running the application directly, or in containers with Podman, it makes sense to write logs to files in a volume, where a log collector can read them. (On Kubernetes or OpenShift, applications log to standard output instead, and the platform collects the logs.)

Create a directory for logs, and link it into the project:

mkdir -p ~/volumes/logs
ln -s ~/volumes/logs mnt/logs

Python’s logging module can be configured with a file. Add it to the root of the project:

logging.confini
[loggers]
keys=root

[handlers]
keys=logfile,logconsole

[formatters]
keys=logformatter

[logger_root]
level=INFO
handlers=logfile,logconsole

[formatter_logformatter]
format=[%(asctime)s.%(msecs)03d] %(levelname)s [%(name)s] - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[handler_logfile]
class=handlers.RotatingFileHandler
level=INFO
args=('mnt/logs/exampleforyou.log', 'a', 10485760, 5)
formatter=logformatter

[handler_logconsole]
class=StreamHandler
level=INFO
args=(sys.stdout,)
formatter=logformatter
  • The root logger sends everything at INFO level or above to two handlers: a file and the console. Uvicorn’s own loggers, including the access log of every request, pass their messages up to the root logger.
  • RotatingFileHandler starts a new file when the log reaches 10 MB (10485760 bytes), and keeps the last 5, so the logs can’t fill the disk. (Without a size, it never rotates.)
  • The format includes the time, level and the logger’s name, such as uvicorn.access.

Tell Uvicorn to use this configuration in main.py:

main.pypython
if __name__ == '__main__':
    configure()
    uvicorn.run(main_app,
                host=settings.CONF_MAIN_APP_HOST,
                port=settings.CONF_MAIN_APP_PORT,
                log_level=settings.CONF_DEBUG_LEVEL,
                ssl_keyfile=settings.CONF_SSL_KEYFILE,
                ssl_certfile=settings.CONF_SSL_CERTFILE,
                log_config="logging.conf")  # NEW

Running the application with python main.py now writes the logs to ~/volumes/logs/exampleforyou.log, as well as the console:

[2026-12-02 15:00:44.168] INFO [uvicorn.access] - 10.164.9.8:59426 - "GET /metrics HTTP/1.1" 200

(With Uvicorn directly, the option is uvicorn main:main_app --log-config logging.conf.) The mnt/logs directory must exist, or the application won’t start.

tip

echo=True in db/db.py logs every SQL statement at INFO level, so they all end up in the log file too. That’s useful while developing, but turn it off in production.