Here is how I setup my python logging for a fastAPI project.
I have the following fastAPI file architecture:
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!
Here are useful links to setup logging
List of all the LogRecord attributes (variables you can put in the log formatter):
logging - Logging facility for Python - Python 3.8.2 documentation
Source code: Lib/logging/__init__.py This module defines functions and classes which implement a flexible event logging…
Good python logging tutorial: