0

I have an api.py file with the following:

from fastapi import FastAPI
import logging
import uvicorn

app = FastAPI(title="api")

LOG = logging.getLogger(__name__)
LOG.info("API is starting up")
LOG.info(uvicorn.Config.asgi_version)

@app.get("/")
async def get_index():
    LOG.info("GET /"
    return {"Hello": "Api"}

The application locally is run with:

uvicorn api:app --reload
INFO:     Will watch for changes in these directories: ['/Users/user/code/backend/api']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [44258] using StatReload
INFO:     Started server process [44260]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

It is not logging any of the startup messages.

Later on when sending a http request to the api:

INFO:     127.0.0.1:50538 - "POST /api/v1/endpoint HTTP/1.1" 200 OK

In the function body there is LOG.info("example") that does not get logged either.

Is there a way to make FastAPI logging work with Uvicorn and also in production (independently of the execution environments like Uvicorn).

Istvan
  • 7,500
  • 9
  • 59
  • 109
  • You might find [this answer](https://stackoverflow.com/a/70899261/17865804) and [this answer](https://stackoverflow.com/a/73464007/17865804) helpful. – Chris Aug 29 '23 at 15:52
  • thanks @chris these are helpful but do not solve my problem. – Istvan Aug 30 '23 at 08:50
  • To log startup messages, please try using a `startup`/`lifespan` event handler, as demonstrated [here](https://stackoverflow.com/a/76322910/17865804) and [here](https://stackoverflow.com/a/73736138/17865804) – Chris Aug 30 '23 at 09:06
  • I think this is a working reproducible example now. – Istvan Aug 30 '23 at 11:38

1 Answers1

1

Be sure to add a StreamHandler or FileHandler and set the level/severity (i.e., DEBUG, INFO, WARNING, etc). The following example is based on this answer and this answer. More details and examples can be found in Python's official documentation page here.

Working Example

from fastapi import FastAPI
import logging
import sys

app = FastAPI(title='api')

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.info('API is starting up')

@app.get('/')
async def main():
    logger.info('GET /')
    return 'ok'
Chris
  • 18,724
  • 6
  • 46
  • 80