Here is how I setup my python logging for a fastAPI project.

I have the following fastAPI file architecture:

main.py
logging.conf
uicheckapp/
--db.py
--services.py
...

First I create a logging.conf file at the root of the project.

This file configures the loggers. I created the root and uicheckapp loggers. The root logger is a special logger. It is the logger that will be used if no other is found.

The uicheckapp logger has the same name as the package in which I have all my code I want to log from. This is very important, because a logger is selected by module name.

At the beginning of the file I set the loggers by loading the “logging.conf” file. This needs to be done once before any “logging.getLogger(…)” calls. This setup can be done in an external dependency that is imported.

Here I get the uicheckapp logger because services.py is in the uicheckapp folder. This is the logger I want to use for most of my application

your logging should work at this point.

Middleware : Logging every request

I also made a middleware that logs the time every request takes.

I generate a unique ID for each request so I can trace which logs come from the same requests.

Buy me a coffee

If you find this article useful consider buying me a coffee :) This helps me publish more useful content!

Computer Engineering Bachelor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store