Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use python logging with uvicorn/FastAPI? [duplicate]

Here is a small application that reproduces my problem:

import fastapi
import logging
import loguru

instance = fastapi.FastAPI()

@instance.on_event("startup")
async def startup_event():
    logger = logging.getLogger("mylogger")
    logger.info("I expect this to log")
    loguru.logger.info("but only this logs")

When I launch this application with uvicorn app.main:instance --log-level=debug I see this in my terminal:

INFO:     Waiting for application startup.
2024-05-02 13:14:45.118 | INFO     | app.main:startup_event:28 - but only this logs
INFO:     Application startup complete.

Why does only the loguru logline work, and how can I make standard python logging work as expected?

like image 779
quant Avatar asked Oct 31 '25 03:10

quant


2 Answers

It's because the --log-level=debug only applies to uvicorn's logger, not your mylogger logger - whose level remains set at WARNING.

If you add a line to the end of your script such as

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s | %(levelname)-8s | "
                           "%(module)s:%(funcName)s:%(lineno)d - %(message)s")

and run, you'll see something like

$ uvicorn main:instance --log-level=debug
INFO:     Started server process [1311]
INFO:     Waiting for application startup.
2024-05-02 16:44:55,736 | INFO     | main:startup_event:12 - I expect this to log
2024-05-02 16:44:55.736 | INFO     | main:startup_event:13 - but only this logs
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

The extra line configures the root logger and adds a console handler with that format, and events logged to the mylogger logger are passed up the hierarchy to the root logger's console handler.

like image 176
Vinay Sajip Avatar answered Nov 01 '25 17:11

Vinay Sajip


Try this: uvicorn app.main:instance --no-access-log

The reasoning is that Uvicorn configures the built-in logging module by default. Passing this flag while starting your application will turn off Uvicorn's access log and allow you to configure custom logging. Source: Settings - Uvicorn

like image 30
marcelovca90 Avatar answered Nov 01 '25 16:11

marcelovca90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!